Reputation: 254
Refer to the given below code:
I am not able to understand that what's happening under the hood that let the confusion between the two points mentioned below:
revArrayInPlace(a)
executes, it change the original value of variable a
but revArray(a)
executes, it doesn't change the original value of variable a
In revArrayInPlace(a)
, if(x[someIndex] = someValue)
replace the original value of x[someIndex]
with somevalue
, then logically x = newArray
should also replace the original value of array x
with new value newArray
when revArray(a) executes
a = [1,2,3,4,5]
function revArray(x) {
var result = [];
for (var i = x.length -1; i >= 0 ; i = i-1) {
result.push(x[i]);
}
x = result;
}
function revArrayInPlace(x) {
for (var i = 0; i<Math.floor(x.length/2); i=i+1) {
var old = x[i];
x[i] = x[x.length - 1 - i];
x[x.length -1 -i] = old;
}
return x;
}
Upvotes: 0
Views: 50
Reputation: 1075209
At the end of revArray
, you're doing this:
x = result;
That does nothing to modify the original array or the original variable (a
, I think) referring to it (but it's a common misunderstanding, you're not the only one!). All it does is modify the value in x
, changing it from being a reference to the original array to being a reference to the new array. Since the next thing you do is exit the function, that doesn't accomplish anything.
In JavaScript, only values are passed into functions, not variables. So:
var a = [1, 2, 3, 4, 5];
revArray(a);
...reads the value from a
and passes that value into revArray
. That value tells the JavaScript engine where the array is, but it has no ongoing connection to the a
variable at all. If you think about it, it has to be that way, because you can pass the result of an expression into a function; then what would assigning to the argument do? :-)
To make revArray
work, return the result:
return result;
...and call it like this:
a = revArray(a);
Example:
var a = [1,2,3,4,5];
function revArray(x) {
var result = [];
for (var i = x.length -1; i >= 0 ; i = i-1) {
result.push(x[i]);
}
return result;
}
a = revArray(a);
console.log(a);
Upvotes: 4