Data types refer to the type of data that can be stored in a variable.
Till now, we learnt how to assign values to variables but there are different types of values that can be assigned to a variable.
These different kinds of values are referred to as data type.
Javascript data types fall into following two broad categories.
1. Primitive types
 These types deal with a single value.

Primitive values can be any of the following types.
A. String
A sequence of characters enclosed between single quotes or double quotes is a String.
A string may also be of more than one words separated by a space.
Examples of string are ‘codippa’, ‘javascript’,¬† ‘learning javascript is fun’ etc.

B. Number

All numbers whether they are whole numbers of decimal number fall into this category of data types.
Examples, 23, 45.65, 0.00001 etc.

C. Boolean

Values of boolean data type are either true or false.

D. undefined

When a variable is declared but has not been assigned a value then its value is undefined. Example,

// declare variable
let x;
console.log(x);  // prints undefined

Type of a variable can be determined using typeof operator followed by the name of the variable. Example, typeof x

E. null
A variable is provided a null value to signify that it holds no value.
A null value is also used to reset the value of a variable to no value.

null is different from undefined in that undefined means that the variable was never assigned a value.

let x;  // x is undefined
x = 10; // x is 10
x = null; // reset the value of x

If you check the type of null and undefined using typeof operator, then it will be object.

2. Reference types
While primitive data types deal with values, reference data type refers to an object. Objects and Arrays are the types that fall under reference data types.

A javascript object is a group of key-value pairs enclosed between curly braces({ and }).
Example, let website = {name: '', type: 'search engine'}.

A javascript array is a group of values of same or different primitive types enclosed between square brackets([ and ]). Example, [10, ‘javascript’, 23.5].

The type of variable holding a reference data type is object. Example,

// variable holding an object 
let website = {name: '', type: 'search engine'}
console.log(typeof website);  // prints object
// variable holding an array
let arr = [10, 'javascript', 23.5];
console.log(typeof arr);  // prints object

Dynamic Typing
Javascript is a dynamically typed language.
This means that the values held by a variable can change at run-time.
A variable can hold a string value at one point and a decimal number or an array at some other point.

// variable with string value
let x = 'codippa';
console.log(typeof x); // prints string
// change its value to decimal
x = 20.5;
console.log(typeof x); // prints number



Leave a Reply