DEV Community

Cover image for Reference Vs Value in JavaScript?
Khwaja Billal Siddiqi
Khwaja Billal Siddiqi

Posted on

Reference Vs Value in JavaScript?

In JavaScript, you can pass by value and by reference. The main difference between the two is that passing by value happens when assigning primitives while passing by reference when assigning objects.
When you pass a primitive type variable like a string or a number into a function, you are passing it by value. This means that any changes to that variable within the function have no effect on the data outside of the function.
On the other hand, when you pass an object into a function, you are passing it by reference. This means that if you change a property of that object within the function, that change will be reflected outside of the function as well.

let myNumber = 10;
let myObject = {value: 20};

function change(number, object) {
    number = number * 2;
    object.value = object.value * 2;
}

change(myNumber, myObject);
console.log(myNumber); // 10
console.log(myObject); // 40

Enter fullscreen mode Exit fullscreen mode

In this example, myNumber is a primitive type and is passed by value into the change function. This means that any changes to the number parameter within the function have no effect on myNumber outside of the function.
On the other hand, myObject is an object and is passed by reference into the change function. This means that when we change the value property of the object parameter within the function, that change is reflected in myObject.value outside of the function.

Follow me on Github & Twitter

Top comments (0)