How Passing Arguments Works Value vs. Reference In JS

How Passing Arguments Works Value vs. Reference In JS: Hello everyone, welcome to the nkcoderz.com website. In this article we will going to discuss about the How Passing Arguments Works Value vs. Reference In JS.

How Passing Arguments Works Value vs. Reference In JS

In JavaScript, arguments are passed to functions by value. However, if the value being passed is an object (including arrays), the reference to the object is passed, not the object itself. So, any changes to the object’s properties will persist after the function has been called.

For example:

let a = 5;
let b = { x: 10 };

function changeValue(a, b) {
  a = 10;
  b.x = 20;
}

changeValue(a, b);

console.log(a);
console.log(b);

Output

5

{ x: 20 }

In this example, the primitive value a is passed by value, so it’s not affected by the function, but the object b is passed by reference, so its properties can be modified by the function.

In JavaScript, primitives (e.g. numbers, strings, booleans) are passed by value, meaning that when a primitive is passed as an argument to a function, a new copy of the value is created in memory, so any changes made to that value inside the function will not persist after the function is executed.

Code For Primitives

For example:

let num = 10;

function addFive(num) {
  num += 5;
}

addFive(num);

console.log(num);

Output

10

On the other hand, objects (including arrays) are passed by reference, meaning that when an object is passed as an argument to a function, a reference to the object is created in memory, so any changes made to the object’s properties inside the function will persist after the function is executed.

Code For Objects

For example:

let obj = { x: 10 };

function addFive(obj) {
  obj.x += 5;
}

addFive(obj);

console.log(obj);

Output

{ x: 15 }

Conclusion

So, when working with objects, it’s important to understand that changes made to the object inside a function will persist after the function is executed. If you want to prevent this, you need to create a copy of the object and work with that instead.

If you liked this post How Passing Arguments Works Value vs. Reference In JS, then please share this with your friends and make sure to bookmark this website for more awesome content.


If You Like This Page Then Make Sure To Follow Us on Facebook, G News and Subscribe Our YouTube Channel. We will provide you updates daily.
Share on:

NK Coderz is a Computer Science Portal. Here We’re Proving DSA, Free Courses, Leetcode Solutions, Programming Languages, Latest Tech Updates, Blog Posting Etc.

Leave a Comment