Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - can modify array passed to function only sometimes

Why does the first function not modify the original array like the second function does?

var a= [3, 4, 5];
function doesNothing(a) {
    a=[1,1,1];
}

function doesSomething(a) {
    a.push(6);
}

doesNothing(a);
console.log(a);     // [3,4,5] not [1,1,1]
doesSomething(a);
console.log(a);     //[3,4,5,6]
like image 397
JimF Avatar asked May 01 '15 01:05

JimF


People also ask

Can you change array in function JavaScript?

That is, there is only one array -- and that same array is changed inside the function. If you wish to be able to change it without fear of affecting the outside, make a copy first. For a simple array this can be done with Array. prototype.

Can you pass an array to a function in JavaScript?

The modern, and easiest way to pass an array to a function is to use the spread operator. The spread operator ( ... ) is simply added before the array.

How do you modify an array in JavaScript?

push() adds item(s) to the end of an array and changes the original array. unshift() adds an item(s) to the beginning of an array and changes the original array. splice() changes an array, by adding, removing and inserting elements. slice() copies a given part of an array and returns that copied part as a new array.

Can you modify an array?

Given an array, we need to modify values of this array in such a way that sum of absolute differences between two consecutive elements is maximized. If the value of an array element is X, then we can change it to either 1 or X.


2 Answers

The first function makes no attempt to modify the array. All it does is assign a new value to the parameter that, when it was called, was given a copy of a reference to the array. The variable a in the first function is just a variable with an object reference as its value. The assignment statement just changes its value, exactly as if your function had

    a = 5;

instead.

Note that you've declared the first function with a as a parameter - that symbol a hides the a outside the function.

The second function does modify the array because it calls a method on the array object that modifies it.

like image 184
Pointy Avatar answered Sep 22 '22 13:09

Pointy


Because in your first function, the statement a = initializes a new variable in local scope (it essentially translates to var a =) completely unrelated to the global a variable, whereas in the second function, you're calling upon and mutating the original array passed into it.

like image 21
Drazen Bjelovuk Avatar answered Sep 21 '22 13:09

Drazen Bjelovuk