DEV Community

Dheeraj Jha
Dheeraj Jha

Posted on

Understanding Assign by Value and Assign by Reference in JavaScript.

Assign by Value:

When assigning a primitive data type (like numbers, strings, or booleans), the value is copied to the new variable. Any changes made to one variable won't affect the other. For example:

let a = 5;
let b = a;
b = 10;

console.log(a); // Output: 5
console.log(b); // Output: 10
Enter fullscreen mode Exit fullscreen mode

Assign by Reference:

When assigning objects (including arrays and functions), the reference to the object is copied, not the actual value. So, any modifications made to the object will affect all variables pointing to it. For example:

let arr1 = [1, 2, 3];
let arr2 = arr1;
arr2.push(4);

console.log(arr1); // Output: [1, 2, 3, 4]
console.log(arr2); // Output: [1, 2, 3, 4]
Enter fullscreen mode Exit fullscreen mode

Understanding these distinctions is crucial for avoiding unexpected bugs and ensuring your code behaves as expected. It's also vital when working with function parameters and returning values.

Keep these concepts in mind while developing in JavaScript, and it will help you write more robust and predictable code. Happy coding! 😄🚀

Top comments (2)

Collapse
 
bkpecho profile image
Bryan King Pecho

Great explanation! Understanding assign by value and assign by reference in JavaScript is key to writing bug-free code.

Collapse
 
thedheerajjha profile image
Dheeraj Jha • Edited

@bkpecho Thanks!!