Dynamic types in javascript – javascript data types

Author: Satz | Date: August 6, 2013

JavaScript has dynamic types, hence a single variable can be used as different types. There are 7 native types in JavaScript. They are String, Number, Boolean, Array, Object, Null and Undefined. JavaScript’s dynamic types feature makes it flexible to reuse the same variable into different types (although it is not recommended to do so). Below is the sample code.

var a;
console.log('typeof a is now,'+ typeof(a));
a = null;
console.log('typeof a is now,'+ typeof(a));
a = 1;
console.log('typeof a is now,'+ typeof(a));
a = "string value";
console.log('typeof a is now,'+ typeof(a));
a = false;
console.log('typeof a is now,'+ typeof(a));
a = [];
console.log('typeof a is now,'+ typeof(a));
a = {};
console.log('typeof a is now,'+ typeof(a));

Executing the above would out log like;

typeof a is now,undefined
typeof a is now,object
typeof a is now,number
typeof a is now,string
typeof a is now,boolean
typeof a is now,object
typeof a is now,object

The same variable transformed its type into different types! The data type for null, array and object are object itself. Undefined type is undefined itself, a string’s type would be string, number’s type would be number and the boolean’s type would be Boolean.

When a variable is declared in JavaScript, it becomes a new object. All the variables and functions defined are the properties of the window object. “window” is the root object and all the JavaScript variables, functions, namespaces, etc. are different properties in window object.