Javascript - Primitive And Reference Values

Introduction

ECMAScript variables have two different types of data: primitive values and reference values.

Primitive values are simple atomic pieces of data, while reference values are objects that may be made up of multiple values.

The five primitive types: Undefined, Null, Boolean, Number, and String, are accessed by value.

Reference values are objects.

Dynamic Properties

Primitive and reference values are defined similarly: a variable is created and assigned a value.

When you work with reference values, you can add, change, or delete properties and methods at any time.

Consider this example:

var person = new Object();
person.name = "First";
console.log(person.name);    //"First"

Here, an object is created and stored in the variable person.

Next, a property called name is added and assigned the string value of "First".

The new property is accessible from that point on, until the object is destroyed or the property is explicitly removed.

Primitive values can't have properties added to them:

var name = "First";
name.age = 27;
console.log(name.age);    //undefined

Here, a property called age is defined on the string name and assigned a value of 27.

On the next line, the property is gone. Only reference values can have properties defined dynamically for later use.

Related Topics