Data types in JavaScript

Inspired from an exercise in Hackerrank.com, I found the opportunity to present you the data types that JavaScript defines, which are the following six:

Arrays and functions are plain objects in JavaScript and they both belong to the object data type. All data types except the object are called primitive or value types. Each variable of this category has its own copy of the assigned value and operating on one of many variables that contain the same value is not affecting the value that is referenced from the other variables. Here is an example pointing that out:

var isDoorOpened = false;
var numberOfDoors = 4;
var nameOfDoor = "the main door";
var aVariableWithAnUndefinedValue;
var aVariableWithANullValue = null;
var aTestVariable = null;

aTestVariable = isDoorOpened;
aTestVarialbe = 1;
console.log(isDoorOpened);
// isDoorOpened's value is still false

The object data type is a reference type which means that inside a variable a reference to the object is assigned. If two or more variables contain the same reference to an object, then when operating on one variable will change the object and since the other variable reference the same object, this will affect the referenced value for all variables. Here is an example:

var human = {
    name: "Christos"
}

var aNewHuman = human;
aNewHuman.name = "Max";
console.log(human.name);
// human.name will not print "Christos" but "Max"

You can find the code of the article here.

comments powered by Disqus