Skip to main content
JavaScriptResourcesWeb Dev

Pass by reference vs Pass by Value

By August 14, 2020July 17th, 2022No Comments
Pass by value

Pass by value

Non-primitive data types are passed by reference compared to primitive data types that are passed by value. As such non-primitive data types are also called reference types.
To understand why they’re called reference types, we need to briefly look at how variables are stored in memory. A fixed amount of memory is allocated to a variable after it is declared. For primitive data types, the actual value in memory is copied over because the value assigned to a variable is immutable and known. Subsequently, exactly how much memory it will take is also then known. For example let user = “Jyoti”, is
“1001010 1111001 1101111 1110100 1101001” in binary.

Pass by reference

Whereas for object data types the address in memory of the object is copied rather than the actual value. As objects can have multiple values, which may or may not fit inside fixed memory. Take for example in the following code, the object called user which has one property to start with. But with time you can keep adding more properties as you like.

let user={
role: 'developer'
};
user.employed = true;
user.name = 'Rocko';

When you console.log the user object, you see it now has all the newly added
properties:

Object {
employed: true,
name: "Rocko",
role: "Developer"
}

Therefore, properties and their values are added after declaring the object. This illustrates that the memory size of reference types is not known in advance. So objects are copied by reference rather than value.
The main differences between Primitive and non-primitive data types are:

  • Primitive types are immutable whereas non-primitive data types can be mutated
  • Primitive data types reference a single value whereas non-primitive data types are a collection of one or more data types
  • Primitive data types are pass by value and non-primitive data types are pass by reference
  • In memory, value is the actual value In memory for rimitive data types, value is an address/reference for non-primitive values

Leave a Reply