Reputation: 3
I am learning javascript. One of the exercises is to write a function that overwrites the values in an array passed in as a parameter. My solution worked within the function, but it did not seem to be passed back from the function. Also if I do the same thing that is not in a function, it also works. After I worked out what the problem was I wrote simplified versions of my solution vs a version that works. But I still don't understand why one works and one doesn't. Is someone able to explain?
Thanks
function reverseArrayInPlace(ary){
// This version is successful
ary[0] = 5;
ary[1] = 4;
ary[2] = 3;
ary[3] = 2;
ary[4] = 1;
console.log("Within reverseArrayInPlace: " + ary);
return ary;
}
function reverseArrayInPlace2(ary){
// This version is not successful
ary = [5, 4, 3, 2, 1];
console.log("Within reverseArrayInPlace2: " + ary);
return ary;
}
var arrayValue = [1, 2, 3, 4, 5];
reverseArrayInPlace(arrayValue);
console.log("After reverseArrayInPlace: " + arrayValue);
var arrayValue2 = [1, 2, 3, 4, 5];
reverseArrayInPlace2(arrayValue2);
console.log("After reverseArrayInPlace2 - why is order wrong?: " + arrayValue2);
// But this works.
arrayValue2 = [5, 4, 3, 2, 1];
console.log("After outer replace of arrayValue2: " + arrayValue2);
Within reverseArrayInPlace: 5,4,3,2,1
After reverseArrayInPlace: 5,4,3,2,1
Within reverseArrayInPlace2: 5,4,3,2,1
After reverseArrayInPlace2 - why is order wrong?: 1,2,3,4,5
After outer replace of arrayValue2: 5,4,3,2,1
Upvotes: 0
Views: 154
Reputation: 3574
You're not saving the results.
Do this instead:
var arrayValue = [1, 2, 3, 4, 5];
arrayValue = reverseArrayInPlace(arrayValue);
console.log("After reverseArrayInPlace: " + arrayValue);
var arrayValue2 = [1, 2, 3, 4, 5];
arrayValue2 = reverseArrayInPlace2(arrayValue2);
console.log("After reverseArrayInPlace2 - why is order wrong?: " + arrayValue2);
or
var arrayValue = [1, 2, 3, 4, 5];
console.log("After reverseArrayInPlace: " + reverseArrayInPlace(arrayValue));
var arrayValue2 = [1, 2, 3, 4, 5];
console.log("After reverseArrayInPlace2 - why is order wrong?: " + reverseArrayInPlace2(arrayValue2));
Upvotes: 1
Reputation: 413916
JavaScript is a pass-by-value (or call-by-value, if you prefer) language. Assigning a new value to a function parameter inside the function has no effect on the outside world. However, using a passed-in reference to an object to modify property values does affect the outside world. You pass in a reference to the array, and then the function can use that reference to stuff new values into the elements of the array.
Your function returns the modified array, but your calling environment ignores that. Change your test:
var arrayValue2 = [1, 2, 3, 4, 5];
arrayValue2 = reverseArrayInPlace2(arrayValue2);
console.log("After reverseArrayInPlace2 - why is order wrong?: " + arrayValue2);
Upvotes: 3