What is the difference between Primitive And Reference Values

Description

Javascript variables may contain two different types of data:

  • primitive values
  • reference values

The values from five primitive types: Undefined, Null, Boolean, Number, and String are primitive value.

Reference values are object references.

Copying Values

Primitive and reference values act differently when copied from one variable to another.

When assigning a primitive value, the value is copied from one variable to the new variable.


var num1 = 5;
var num2 = num1;
console.log(num1);
console.log(num2);

The code above generates the following result.

Copying address

When assigning a reference value, the variable value is also copied into the new variable.

The value from reference type is an address to an object.

Once the operation is complete, two variables point to the same object, so changes to one are reflected on the other.


var obj1 = new Object();
var obj2 = obj1;
obj1.name = "XML";
/*from   w w w  .ja  v  a 2 s .  c o  m*/
console.log(obj2.name);    //"XML"

In this example, the variable obj1 is filled with a new instance of an object. This value which is address to the object is copied into obj2, both variables are now pointing to the same object. When the property name is set on obj1, it can later be accessed from obj2.

The code above generates the following result.





















Home »
  Javascript »
    Javascript Introduction »




Script Element
Syntax
Data Type
Operator
Statement
Array
Primitive Wrapper Types
Function
Object-Oriented
Date
DOM
JSON
Regular Expressions