Basic Concept of Javascript Data Types & Typeof Operator
Data Types in JavaScript
In programming, data types is an important concept. There are six basic data types in JavaScript which can be divided into three main categories:
- Primary : String, Number, and Boolean are primary data types.
- Composite: Object, Array, and Function are composite data types.
- Special : Undefined and Null are special data types.
Let’s discuss each one of them in detail.
The String Data Type
The string data type is used to represent textual data. While writing string data we need to use single or double quotes surrounding one or more characters, as example-
The Number Data Type
The number data type is used to represent positive or negative numbers with or without decimal place, as example-
The Number data type also includes some special values which are:
Infinity
,-Infinity
andNaN
.
The Boolean Data Type
In Boolean data type, it has only two values:
true
orfalse
. It is used to store values like yes (true
) or no (false
). As for Example-
We can also found boolean value in any comparisons from a program.
The Undefined Data Type
The undefined data type is a special data type which have only one value,
undefined
. If we declare a variable but never set its value, it will showundefined
. Example-
The Null Data Type
It is another special data type which have only one value -the
null
value. It means there is no value but not like empty string (""
) or 0, it means just nothing. Example-
The Object Data Type
The
object
is a complex data type where we can store collections of data. Anobject
is defined by properties which have key(name) and (value). The property value is stored into curly braces {}.A property key (name) is always a string, but the value can be any data type, like strings, numbers, booleans, arrays, function and other objects. Example-
The Array Data Type
An array is a type of object used for storing multiple values in single variable. An array can contain any data type-numbers, strings, booleans, functions, objects, and even other arrays.
The value of array is known as its index. The array index starts from 0, so that the first array element is
arr[0]
notarr[1]
. Example-
The Function Data Type
In JavaScript, the function is also an object. So, it is possible to assign them to variables. We can also pass any parameter in function. Example-
The typeof Operator
The
typeof
operator can be used to find out what type of data a variable or operand contains. It can be used with or without parentheses (typeof(x)
ortypeof x
).