i expect the elements in arr be reversed, but it still log as [‘a’,’b’,’c’,’d’,’e’]
i think i am doing some fundamental problem but i cannot figure out what it is
function reverseArray(array) {
let array02 = [];
let len = array.length-1;
for (let i=0; i<=len; i++){
array02[len-i] = array[i];
}
array = array02;
return array;
}
var arr = ['a','b','c','d','e'];
reverseArray(arr);
console.log(arr);
4
Answers
Yes, the fundamental point you’re missing is that you’re doing basically this:
and expect the variable
arr
to change its value. This doesn’t work in Javascript, because Javascript passes arguments by value and any assignment to a function argument (array = ....
) cannot affect a variable in the calling code.What you need here is either return a new value and assign it in the caller code
or change the value itself, and not the variable:
You can modify the function to directly reverse the elements of the input array without creating a new array like this:-
You are re-assign array to array02 inside the function. That is why main array is lost. Try this one for reversing array.
You can also use array.reverse function.
Or like this way.
What you are doing is assigning array1 to array2 inside
reverseArray(array)
function. By doing so you are losing the original array.