Is JavaScript a Pass-by-reference or Pass-by-value language?
In this snippet, we are going to look into pass-by-reference and pass-by-value in JavaScript.
JavaScript is considered a pass-by-value language, but at the time a variable refers to an object, the value becomes a reference of that object.
Now, let’s see what is pass by value and pass by reference.
Pass By Value
In pass by value, a function may be called by directly passing the value of the variable as an argument. If you change the argument inside the function, it will not affect the variable that is passed from outside the function.
As JavaScript is always a pass by value, changing the variable’s value will not change the underlying primitive (number or string).
Let’s demonstrate it in the example below:
The output will be as follows:
Before Call by Value Method var1 =100 var2 =200 Inside Call by Value Method var1 =10 var2 =20 After Call by Value Method var1 =100 var2 =200
But in case a variable refers to an object that includes an array, the value is the reference to the object.
Pass by value is a safer way of programming, which prevents the programmer from overriding variables inside the functions. JavaScript and other modern programming languages employ it when it comes to primitives.
Pass By Reference
In pass by reference, a function may be called by directly passing the reference/address of the variable as an argument. If you change the argument inside the function, it will affect the variable passed from outside the function.
In JavaScript, objects and arrays are passed by reference.
Here is an example:
Output will be :
Before Call by Reference Method {a: 1} Inside Call by Reference Method {a: 100} After Call by Reference Method {a: 100}
Primitives in JavaScript
The simplest elements of a programming language are called primitives. They differ from language to language but are generally the most basic immutable value.
The following JavaScript primitive data types are passed by value: string, boolean, number, null, undefined.
The primitives are copied by their value means that the variable is passed accessed by its value.
Primitives are immutable, which means that their values can’t be changed but can be reassigned.
Reference Type (Object)
Objects in JavaScript belong to the reference type.
Unlike primitives, the size of the reference value is dynamic; therefore, JavaScript stores the reference values on the heap.
The object is a collection of properties that can reference any data type, including objects and primitive values.You can create objects with figure brackets {…} with a list of properties.
Generally, objects pass through almost any aspect of JavaScript. Hence it is one of the first things to learn.