Unexpected output when reversing string


I’m trying to work my way through some beginner/intermediate JavaScript challenges as despite learning a lot about JS in the last few months, I never take enough time out of my day to actually code. I find that whilst I know a fair amount about the syntax and a little about what is available to me, I struggle to actually convert an idea into working JavaScript code.

Here I am tasked with reversing a string, seems simple enough… but I’m having an issue. Can anyone please explain why the console prefixes the outputted string with NaN? Apologies if this is something really simple, but I can’t seem to work it out.

function stringRotate(){

var string = ‘javascriptchallenges’;
var newString;

for(var i = string.length; i > -1; i–) {
newString += string[i];


//Outputs NaNsegnellahctpircsavaj

The first time the loop runs, the index variable (i) is the length of the string, but since arrays start at 0, it’s looking for a character in the string that doesn’t exist, so i becomes undefined. The newString variable has no type yet, so JavaScript treats it as a number when you try to add undefined to it, which is why you’re getting NaN. After this, the code runs as intended.

Changing the for loop to use var i = string.length - 1; should fix it.


What kwouk said…
but you’ll have “undefined” prepended to it since newString is initially undefined.
Try initializing it to “”.


Perfect! Thank you @kwouk and @8-up, that makes a lot more sense.