DEV Community

Muhammad Hamza Hijazi
Muhammad Hamza Hijazi

Posted on

Is Javascript Pass by Value or pass by Reference ?

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


Enter fullscreen mode Exit fullscreen mode

Lets see another example

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

Enter fullscreen mode Exit fullscreen mode

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

Enter fullscreen mode Exit fullscreen mode

Discussion (1)