Skip to content

JavaScript – Primitive vs Reference Types

Two areas of confusion around JavaScript primitive vs reference types -
1. If every thing in JavaScript is an object
2. Passed by value vs passed by reference

1. If every thing in JavaScript is an object

This is untrue since JavaScript clearly defines the following primitive types -
1. Number
2. Boolean
3. String
The confusion arises because JavaScript allows us to call methods on primitive types. For example, these are all legal statements -

1['toString']() // outputs 1 as a String

1..toString() // outputs 1 as a String. Note: 1. means 1 followed by decimal

true.toString() // outputs true as a String

"Some Str".toString() // outputs Some Str as a String

It is important to understand how this works. The Number 1, the Boolean true and the String “Some Str” are truly primitive types by themselves, but, when a method is called on them, JavaScript creates a transient or temporary object for the primitive type and tries to call the method. For example, in the case of the Number 1, a transient object is created as follows -

new Number(1) // Transient object

It is also important to understand that the transient object is ‘transient’ and is garbage collected as soon as the method has returned.
From the explanation and example above, we can see, this object like behavior of primitive types is a feature of the language and not of the primitive types themselves.

2. Passed by value vs passed by reference
As a rule of thumb in any programming language, primitive types should be passed by value, whereas, reference types, passed by reference. In JavaScript this is true, except for Strings.
So, Number and Boolean are passed by value. Whereas, everything else, including Array and Function( represented as objects in JS) are passed by Reference. So, what is the deal with Strings? Here is an explanation –

Since a String can be of infinite size, passing it by value will be inefficient, therefore, JavaScript chooses to pass Strings by reference. The good part is, Strings in JavaScript are immutable, meaning once a String object is created it cannot be modified. There is no method available on String that allows us to modify it. For example, Strings do not provide us any such method – insertCharAt or replaceCharAt. This also means, as Javascript developers, we do not have to worry about Strings ever getting modified, even though, they are passed by reference. Also, note, although, Strings are passed by reference for efficiency, they maintain their primitive nature when we compare two Strings. Take the following for example -


"abc" === ("ab" + "c") // true, since values are compared

In short, the issue of how Strings are passed in JavaScript is really not an issue because Strings are immutable.

Follow

Get every new post delivered to your Inbox.