DEV Community

loading...

Is Javascript Pass by Value or pass by Reference ?

hijazi313 profile image Muhammad Hamza Asif ・1 min read

It's a question which you will mostly hear from your interviewer. But does JavaScript pass variables by Value or by Reference ? There are good chances that if you are fresher or new to Javascript you wouldn't answer this question correctly owing to vague knowledge of how Javascript works behind the scenes, but don't worry ,it's totally normal for a new person.
And the answer to this is that Javascript pass variables by both value and reference but it depends on the data type of the variable we are working with. Primitive data types such as Strings, Booleans, Numbers, Null, , Symbol they are passed by value on the other hand Non-primitive data types such as Objects and Arrays are passed by reference

But what really is pass by Value and Pass by reference ?

Pass by value

When the variables are passed by value we target the value being passed not the actual variable. Always remember only primitive data types in Javascript use pass by value


var a = 1: 
function passByValue(a){
    a = 3
 }
passByValue(3)
console.log(a) // result is 1


Lets see another example

let age = 55
let myAge = age
myAge = 27
age //55

Pass By Reference

When the variables are passed by reference it means we point to actual variable. Any changes on the variable will directly effect the original declared variable. Remember Non-primitive data types perform pass by Reference in Javascript.


const car = {
  color: 'blue'
}
const anotherCar = car
anotherCar.color = 'yellow'
car.color //'yellow

Discussion

pic
Editor guide
Collapse
zoedreams profile image
☮️✝️☪️🕉☸️✡️☯️

Don't believe the hype. All arguments in JS are performed by "copy by reference". Which is why you need to use Object.assign({}, ) in order to clone objects. Primitives just look like they work that way. Everything in jS is a function, even the primitives, and even .prototype itself.

Using context dependency injector and factory service architecture you are able to exploit the performace of pass by copy of reference and avoid the garabe collector.. Look up the project LokiJS.

Thank you for sharing