Data types in JavaScript

JavaScript

In this article you will learn data types in JavaScript. Basically there are two data types in JavaScript i.e. first is Primitive data types and second is Non-Primitive data types. Data types specify the value of the variable that is string, number, boolean, object, array etc. You can find type of the variable using typeof operator in JavaScript.

There are 6 primitive data types and 3 non-primitive data types in javascript.

Primitive Data Types

  • string – represents collection of characters e.g. \”hello\” / words or sentence
  • number – represents numeric values e.g. 100 / integers, floats, etc
  • boolean – represents boolean value / true or false
  • null – represents null i.e. no value at all / no value
  • undefined – represents undefined value / a declared variable but hasn’t a value
  • symbol – a unique value that’s not equal to any other value / unique identifiers

Example:

var a = 100; // number
var b = "abc"; // string
var c = true; //  boolean
var d = null; // null
var e = undefined; //  undefined
var f = Symbol(); // symbol

Non-Primitive Data Types

  • Object – represents collection of data in the key/value pair using curly braces {..}
  • Array – represents collection of data(string, number, boolean) using square bracket […]
  • RegExp – represents regular expression / pattern of characters

Example:

var obj = {"name": "abc", "age": 40} // Object
var arr = ["abc",40] // Array
var reg = /\\w+/ //regexp

JavaScript is a loosly type language, means you don’t need to specify the type of the variable because it is automatically bind the data type. You need to use var, let or const keyword to specify the data type. It can hold any type of values such as numbers, strings etc.

typeof Operator

If you want to find type of the variable then you can use typeof operator. Typeof operator finds the type of the variable.

Example:

typeof(100) // number
typeof("abc") // string
typeof(true) //  boolean
typeof(null) // object
typeof(undefined) //  undefined
typeof(Symbol()) //  symbol

var obj = {"name": "abc", "age": 40}
typeof(obj) // object
var arr = ["abc",40]
typeof(arr) // object
var reg = /\\w+/
typeof(reg) // object

In JavaScript, type of the non-primitive data types are object and type of the null is also object. We will discuss later at this point. In next article we will explain about difference between null and undefined in JavaScript.

If you want to improve this article or you find anything wrong/incorrect in this article then please leave a message using below comment box.