Javascript and call by sharing

Before diving into understanding what is call by sharing. Let me show you a weird situation that I encountered.

Let’s say I have a variable of type number initialized to 1 and I want to increment its value by 100 inside a function.

See the code below :

var a = 1;
function incrementByHundred(a){
a += 100;
};
incrementByHundred(a); //calling the function with a=1

Now

Lets check if it really got incremented by 100 or not.

console.log(a); //outputs 1

Apparently, It didn’t.

So, I guess the function has its own scoped variable ‘a’ which got incremented and it didn’t worked on the one which is in the outer scope.

Now let me try this with an array.

var fruits = ["banana","apple","grapes"];
function addAFruit(fruits){
fruits.push(“guava”);
}
addAFruit(fruits);
console.log(fruits); //outputs :["banana","apple","grapes","guava"];

Here I have an array with 3 elements and I tried to modify (add another element) inside a function.

It worked with arrays, the ‘fruits’ array has now 4 elements with guava as new element.

But why it didn’t behave the same way in the former case with number type variable ?

The answer is :

“Primitive parameters (such as a number) are passed to functions by value in JavaScript and non-primitive parameters (such as Array) are passed to functions by reference.”

This evaluation strategy is often referred as call by sharing.

Wondering what does ‘pass by value’ and ‘pass by reference’ means?

“Pass-by-value means the data associated with the variable is actually copied when passed to the function and any modifications made by such function to such variable will be lost when the variable goes out of scope of the function’s body when the function returns.

While pass-by-reference means the data associated with the passed variable is not copied when passed to the function, and thus any modifications made by the function to the passed variable will be retained in the program after the function call terminates.”

As we have seen above that the arrays are passed by reference and if we make any modifications inside the function then it is going to return outside as well. But what If I don’t want the changes to be retained? In other words I want to pass array as argument by value.

Passing array by value is also possible and one way to do that is using slice() method.

var fruits = ["banana","apple","grapes"];
function addAFruit(fruits){
fruits.push(“guava”);
}
addAFruit(fruits.slice());
console.log(fruits); //outputs :["banana","apple","grapes"];

Conclusion:

If you ever want to change some values inside a function and expect it to be like that always.Then use objects.

Thanks!

Show your support

Clapping shows how much you appreciated Arun Kumar’s story.