exercise 2: baby steps | new to node, not to JS and this baffles me

46 views
Skip to first unread message

Lowen Fan

unread,
Sep 9, 2017, 4:01:39 PM9/9/17
to nodejs
Hi guys, I've been programming quite a while in JS. But am a newbie to Node. What a great app learnyounode is!

But this baffled me, perhaps someone cal explain this to me:

'strict mode';

var result;
for (var i = 2; i < process.argv.length; i++) {
result += Number(process.argv[i]);
}

console.log(result);

This always returned NaN. When I console log each iteration, I always end up with an extra iteration which has the value of NaN. Adding them up results into NaN. 

But when I do this:

'strict mode';

var result = 0;
for (var i = 2; i < process.argv.length; i++) {
result += Number(process.argv[i]);
}

console.log(result);

Everything is fine and the program works as expected.

Who can enlighten me??

Calogero Mandracchia

unread,
Sep 9, 2017, 4:34:17 PM9/9/17
to nodejs
Hi!

In JS you need to initialize a variable or it will be "undefined".
Even in the browser, you can try right now in the browser's console with "typeof result".
let result =+ Number() is:
result = undefined + Number() -> NaN

That's it!
Reply all
Reply to author
Forward
0 new messages