Fundamentals 10 min read

Understanding JavaScript Primitive vs Reference Types: Key Differences Explained

This article explores JavaScript’s primitive and reference types, detailing their immutability, assignment behavior, memory storage, comparison methods, and the role of wrapper objects, supplemented with clear code examples and diagrams to illustrate how values and objects are handled in memory.

ITFLY8 Architecture Home
ITFLY8 Architecture Home
ITFLY8 Architecture Home
Understanding JavaScript Primitive vs Reference Types: Key Differences Explained

Inspired by kraaas’s article on primitive and reference types, I added my own observations and understanding.

JavaScript Primitive Types

JavaScript primitive types include: undefined, null, number, boolean, and string. Primitive values are accessed by value, meaning the actual value stored in the variable is operated on.

1. Primitive values are immutable

Any method cannot change the original primitive value, for example a string:

var name = "change";
name.substr(); //hang
console.log(name); //change
var s = "hello";
s.toUpperCase(); //HELLO
console.log(s); //hello

These examples show that the original variable’s value never changes; methods return new strings that are unrelated to the original variable.

Even when reassigning:

var name = "change";
name = "change1";
console.log(name); //change1

Here the primitive string "change" itself cannot be altered; the variable name simply points to a different string value. The change is only a change of the pointer, not the primitive value itself.

2. Primitives cannot have properties or methods

var p = "change";
p.age = 29;
p.method = function(){ console.log(name); };
console.log(p.age); //undefined
console.log(p.method); //undefined

Attempting to add properties or methods to a primitive results in undefined, reinforcing their immutability.

3. Primitive assignment is a simple copy

Assigning a primitive value to another variable creates an independent copy.

var a = 10;
var b = a;
a++;
console.log(a); //11
console.log(b); //10

After the copy, a and b are completely independent; modifying one does not affect the other.

4. Primitive comparison is by value

var person1 = '{}';
var person2 = '{}';
console.log(person1 == person2); // true

5. Primitives are stored in the stack

Example variables:

var name = "jozo";
var city = "guangzhou";
var age = 22;

These values reside in the stack, which holds both the identifier and the actual value.

JavaScript Reference Types

Reference types (objects) include Object, Array, Function, Date, etc.

1. Reference values are mutable

var o = {x:1};
o.x = 2; // modify property
o.y = 3; // add property
var a = [1,2,3];
a[0] = 0; // modify element
a[3] = 4; // add element

2. References can have properties and methods

var person = {};
person.name = "change";
person.say = function(){ alert("hello"); };
console.log(person.name); //change
console.log(person.say); //function(){alert("hello");}

3. Reference assignment copies the object reference

When assigning one reference variable to another, the object’s address in heap memory is copied, so both variables point to the same object.

var a = {};
var b = a;
a.name = "change";
console.log(a.name); //change
console.log(b.name); //change
b.age = 29;
console.log(a.age); //29
console.log(b.age); //29

Thus, changes through either variable affect the same underlying object.

4. Reference comparison checks the reference

var person1 = {};
var person2 = {};
console.log(person1 == person2); //false

Even though the objects look identical, they reside at different heap addresses, so the comparison returns false.

5. References are stored in both stack and heap

The stack holds the variable identifier and a pointer to the object in heap memory.

Example objects:

var person1 = {name:"change1"};
var person2 = {name:"change2"};
var person3 = {name:"change3"};

Wrapper Types (Wrapper Objects)

Consider the following code:

var s1 = "helloworld";
var s2 = s1.substr(4);

Although strings are primitives, they can call methods like substr because ECMAScript automatically creates a temporary wrapper object (String) to provide these methods.

ECMAScript defines three special reference types—Boolean, String, and Number—known as wrapper objects. When a primitive is accessed, the engine creates a corresponding wrapper instance, invokes the method, then discards the temporary object.

Create an instance of the wrapper type (e.g., new String("helloworld")).

Invoke the specified method on the instance (e.g., substr(4)).

Destroy the temporary instance.

This transient nature explains why primitives cannot retain added properties or methods, unlike objects created with new that persist for the lifetime of the scope.

Source: http://www.codeceo.com/article/javascript-base-type-ref-type.html

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaScriptMemory ManagementReference Typesprimitive typeswrapper objects
ITFLY8 Architecture Home
Written by

ITFLY8 Architecture Home

ITFLY8 Architecture Home - focused on architecture knowledge sharing and exchange, covering project management and product design. Includes large-scale distributed website architecture (high performance, high availability, caching, message queues...), design patterns, architecture patterns, big data, project management (SCRUM, PMP, Prince2), product design, and more.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.