Table of contents
In JavaScript, variables are containers that store data values. The way that JavaScript handles variables are different from other programming languages such as C++ or Java, and it's important to understand the difference between "call by value" and "call by reference".
Call by Value
When a variable is assigned a primitive data type value (number, string, boolean, null, or undefined), it is stored in memory as its value. If a new variable is created and assigned the value of the first variable, it will have a separate memory location, and changes to the second variable will not affect the value of the first variable. This is called "call by value".
For example:
let x = 10;
let y = x;
y = 20;
console.log(x); // 10
console.log(y); // 20
In this example, x
has a value of 10, and y
is assigned the value of x
. When y
is changed to 20, the value of x
remains unchanged at 10.
Call by Reference
On the other hand, when a variable is assigned an object (including arrays), it is stored as a reference to the object in memory. This means that any changes made to the object will affect all variables that reference it. This is called "call by reference".
For example:
let a = [1, 2, 3];
let b = a;
b.push(4);
console.log(a); // [1, 2, 3, 4]
console.log(b); // [1, 2, 3, 4]
In this example, a
is an array with values [1, 2, 3]
, and b
is assigned the reference to a
. When the push()
method is called on b
, the value of a
is also updated to [1, 2, 3, 4]
.
Conclusion
In conclusion, understanding the difference between "call by value" and "call by reference" is crucial in writing efficient and effective JavaScript code. Always keep in mind that primitive data types are passed by value and objects are passed by reference, and you'll be well on your way to writing great JavaScript code.