Hello there, fellow JavaScript enthusiasts! Today, we're going to dive into the intriguing topic of pass by value vs pass by reference in JavaScript. This concept is crucial to understand because it affects how we work with variables and how they are passed to functions.
In JavaScript, primitive data types such as numbers, strings, booleans, null, and undefined are passed by value. This means that when you pass a primitive value to a function, a copy of that value is created and passed to the function. Let's illustrate this with an example:
function changeValue(num) {
num = 42;
console.log("Inside function:", num);
}
let myNumber = 10;
console.log("Before function call:", myNumber);
changeValue(myNumber);
console.log("After function call:", myNumber);
In this example, we have a function called changeValue
that takes a number as a parameter and assigns it a new value of 42. We then declare a variable myNumber
and assign it a value of 10.
When we call the changeValue
function and pass myNumber
as an argument, a copy of myNumber
is created and assigned to the num
parameter inside the function. Therefore, modifying the value of num
does not affect the original value of myNumber
. As a result, the output will be:
Before function call: 10
Inside function: 42
After function call: 10
On the other hand, objects (including arrays and functions) in JavaScript are passed by reference. This means that when you pass an object to a function, you are actually passing a reference to that object. Any modifications made to the object inside the function will affect the original object. Let's see an example:
function changeName(person) {
person.name = "John";
console.log("Inside function:", person);
}
let myPerson = { name: "Jane" };
console.log("Before function call:", myPerson);
changeName(myPerson);
console.log("After function call:", myPerson);
In this example, we have a function changeName
that takes an object person
as a parameter and modifies its name
property. We declare an object myPerson
with an initial name
of "Jane".
When we call the changeName
function and pass myPerson
as an argument, a reference to myPerson
is passed to the person
parameter inside the function. Thus, any changes made to person
will be reflected in the original myPerson
object. The output will be:
Before function call: { name: "Jane" }
Inside function: { name: "John" }
After function call: { name: "John" }
Understanding the difference between pass by value and pass by reference is crucial when working with JavaScript. It helps us predict how variables will behave when passed to functions and ensures we don't encounter unexpected side effects.
That's all for today's JavaScript journey! I hope this explanation with real-world examples has shed some light on the pass by value vs pass by reference concept. Happy coding, and until next time!
Follow me in X/Twitter, LinkedIn
Email : ashsajal@yahoo.com