I'm a JavaScript beginner and I've written the snippet below which in my mind should return an array: [5, 4, 3, 2, 1], but instead it returns [5]. I realize there are better ways to achieve the result, but what I'm trying to understand is why my solution doesn't work.
function reverseArray(array) {
for (var i = 3; i >= 0; i--)
array.concat(array.slice(i,i+1));
for (var i = 3; i >= 0; i--)
array.shift();
return array;
};
var arrayValue = [1, 2, 3, 4, 5];
reverseArray(arrayValue);
console.log(arrayValue);
// JS Bin returns: [5]
The shift method appears to work, but the concat/slice code doesn't seem to alter the array. Why not? When I test the line as stand alone code it works fine. Any explanation would be greatly appreciated. Thanks!
arrayValue.reverse()the concat/slice code doesn't seem to alter the array. Why not?because neitherconcatnorslicemodify the array. It's a boring explanation, I know, but it's the explanation.