JavaScript: Call by Value vs Call by Reference
While I was reading a review comment from one of the senior programmers, I started to wonder: is JavaScript pass a value to a function by copying it(Call by Value) or just passing the pointer of it(Call by Reference).
In fact, not even once I have read about this topic from my study of JavaScript(surprisingly, yes), here I have made a toy example that will show how passing values to functions in JavaScript works.
So we can confirm that in JavaScript, a value is called by reference: you can modify a variable outside a function by calling that function.
However, a small notification should be made: primitives are not JS objects, so the comparison operator ===
will always return true as long as the values of two variables of primitive values are the same. This point will be clearer if we look at the following example:
You see, the variable number
is not mutated whereas array
is. So passing reference is only for object variables: primitives are copied.
Additionally, I just wanted to check how the Array#map
method in JavaScript works. We all know that it returns a new array object, but from simple curiosity, does it regenerate an array of objects when it refers to an outer object as well? What I mean is like the following case:
const array = [{one: 1}, {two: 2}];
const object = {three: 3};const array2 = array.map(element => element);
const array3 = array.map((element, index) => {
if (index === 1) {
return object;
}
return element;
});// Question:
// 1. array === array2 ?
// 2. object === array3[1] ?
And the result is somewhat interesting: the elements in the array itself are copied, but referring to the outer variables as return values is just referring: no coping. This subtle difference would be hardly noticeable unless one is involved in highly sophisticated JS array-related works like React or Redux developments.
In Summary:
- JavaScript passes object variables to arguments of functions by passing their references(pointers). However, primitives are passed as their copied values.
Array#map
basically copies each of array elements, but when it refers to an outer variable, that variable is passed as a referrence.