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:
- when
revArrayInPlace(a)executes, it change the original value of variableabut - when
revArray(a)executes, it doesn't change the original value of variablea
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 xwith 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;
}
a. It changes the contents of the array, butaremains the same; it continues to refer to the same array object.