There are two little mistakes you've made.
The first one is the semicolon at the end of the line here:
for (var i = x.length - 1; i >= 0; i--);
Due to that, the stuff in the brackets in the following lines, is not the loops body. It's a seperate statement. The loops body is that single semicolon ;
.
Therefore what happens is that the loop runs, till the end condition is met (when i
is -1), then the block behind it runs, and does:
{
newwarray+=x[i]
}
And the -1
position of x
is undefined
. Now if you add an array and undefined
, both the array and undefined will be casted to a string (an empty array is turned into an empty string), and you end up with "undefined"
.
To make it working, remove the semicolon, and .push
to the array:
for (var i = x.length - 1; i >= 0; i--) {
newwarray.push(x[i]);
}
As a sidenote, the first mistake was only possible because you used var
, which declares i
not only in the loop's body, but in the whole function. I strongly recommend using let
to spot such errors more easily:
for(let i = 1; i < 0; );
{
console.log(i); // ReferenceError: i is not defined
}