Are values passed by reference or by value in JavaScript?
By Flavio
Published · Updated
Tagged: JavaScript
Are values passed by reference or by value in JavaScript? Primitives pass by value, objects are passed as a reference to the same object.
The answer is: it depends!
Primitive types are passed by value.
There are 7 primitives: string, number, bigint, boolean, undefined, symbol, and null. bigint arrived in ES2020.
Everything that’s not a primitive type is an object. Arrays are objects. Functions are objects.
JavaScript always passes by value. For objects the value is a reference to the same object. People call this “pass by sharing”. Mutating a property shows up outside the function. Reassigning the parameter does not change the caller’s variable.
When you pass a number to a function, it’s copied into the function:
const increment = num => {
num = num + 1
}
const num = 2
increment(num)
console.log(num) //2
If you pass an object, the function gets a copy of the reference. Modify a property, and the original object changes:
const increment = num => {
num.value = num.value + 1
}
const num = {
value: 2
}
increment(num)
console.log(num.value) //3
Reassign the parameter, and the caller’s variable stays the same:
const replace = num => {
num = { value: 10 }
}
const num = {
value: 2
}
replace(num)
console.log(num.value) //2Want me to talk about your product? You can sponsor this site.
Related posts about js: