JavaScript has no rules for the type of data that a variable must hold. The type and value can change.
JavaScript divides the variables into two major types: Primitive and Reference. Primitive variables are simple atomic pieces of data and Reference variables are objects of multiple values.
The five primitive types are: Undefined, Null, Boolean, Number, and String. We access these variables by the value that is stored in the variable. Objects are accessed by reference to the memory location where the object is stored.
JavaScript object properties and methods can be added, changed or deleted at any time in the lifetime of the variable. You can’t do that with primitive variables.
var cat = new Object(); cat.color = "black"; alert(cat.color); // black var cat = "Midnight"; cat.color = "black"; alert(cat.color); // undefined
Copying primitive variables results in two different variables. Copying reference variables results in two variables that point to the same object. When the object is changed, both variables will point to that changed object.
var cat1 = new Object(); var cat2 = cat1; cat1.color = "black" alert(cat2.color); // black
JavaScript variables passed to functions are always passed by value. However, since the value of the reference variable is a reference to an object, the changes to the object inside the function will be reflected in the object outside the function. If however, the object variable is set to point to a different variable, that new object is not accessible outside the function.
function mydouble(i) { i += i; return i; } var x=10; y = mydouble(x); console.log(x); // 10 console.log(y); // 20 function setx(obj) { obj.x = 10; obj = new Object(); obj.x = 20; } var obj = new Object(); setx(obj); console.log(obj.x); //10 A reference to the original object was passed in because the VALUE of the variable was a reference to the object, not a copy of the original object
JavaScript function arguments can be thought of as local variables, they are destroyed when the function finishes execution.
The typeof
operator is the best way to tell if a variable is a primitive variable and will also tell us what type of primitive variable. For reference variables, the instanceof
will let us know if a variable is a reference to a specific object, array, or regular expression. Since all reference values are instances of objects, then instanceof
will always return true
for reference variables. Using instanceof
on primitive variables always returns false.
var x = new Object(); var y = x instanceof Object; //true var x = "10"; var y = x instanceof Object; //false