JavaScript — Pass By Value vs Pass By Reference (Email: ramkumarkhub@gmail.com, WhatsApp : (+91) 7709330265
As we know this is the very good topic and interview question.
When I was new in JavaScript, was always confused with pass by value and pass by reference.
In this article I will try to explain both the things with the example.
Pass by Value:
In this method complete value assigned to destination variable means new variable and old variable both will be pointed to different different memory location.
So When we change secondary variable at that time our primary variable will not change.
Below is the Best Example for the same:
let name = “test”;
let copyName = name; // This is pass by value because strings and numbers are always pass by reference.copyName = “test user”;
console.log(copyName) // test user
console.log(name) // test
so in above case when we assigned name variable to copyName and when we changed copyName value at that time name remains the same because strings and numbers are pass by reference.
Pass By Reference:
In this Method only reference assigned to the destination variable means new variable and old variable will be pointed on the same memory location and so when we change secondary variable at the same time primary variable’s value will be change.
Below is the best example for the same:
let obj = {name: “test”}
let obj2 = obj // Pass by reference
console.log(obj) // {name: “test”}
obj2.name = “test user”;
console.log(obj2) // {name: “test user”}
console.log(obj) // {name: “test user”} // why its changed ?
We might suppressed that why obj is changed ? because Objects are pass by reference so when we assign any one object variable to another object variable by default it becomes pass by reference.
I hope you understand the exact difference between pass by value and pass by reference.
Feel free to contact me if you have any questions or concern rearing any front end technologies.
Email: ramkumarkhub@gmail.com
Phone: +91 7709330265