DEV Community

Dheeraj Jha
Dheeraj Jha

Posted on

2 1

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! 😄🚀

Image of Datadog

How to Diagram Your Cloud Architecture

Cloud architecture diagrams provide critical visibility into the resources in your environment and how they’re connected. In our latest eBook, AWS Solution Architects Jason Mimick and James Wenzel walk through best practices on how to build effective and professional diagrams.

Download the Free eBook

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!!

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post