Been heavy into javascript since starting FCC back in May.
Now I have made it to the node.js tutorial and I am not recognizing some syntax.
The js that I have commented out below is the javascript I have come to know for incrementing a variable.
But now, not only does it seem Number(int) is the only thing that will work here, but also node.js treats it as if “sum” was an arra and I had written sum.push(process.argv[i]); !!!
var sum = 0;
for (var i = 2; i < process.argv.length; i++) {
// sum = sum+(process.argv[i]); this treats sum as an array and pushes (process.argv[i]); to the array!!!???!!!
sum += Number(process.argv[i]);
}
console.log(sum);
Is this still javascript or does node.js use its own particular flavor of js?
No, that treats it like an array as well rather than incrementing an integer
var sum = 0;
for (var i = 2; i < process.argv.length; i++) {
// sum = sum+(process.argv[i]); this treats sum as an array and pushes (process.argv[i]); to the array!!!???!!!
//sum += Number(process.argv[i]);
sum = sum+process.argv[i];
}
console.log(sum);
Going to check out Jenov’s answer when I get back to this on my lunchbreak - I think that may be where I am going wrong. Just relieved to not see anyone saying “Node.js has its own flavor of js” Looks like the error is once again somewhere between chair and keyboard.
sum = sum + (process.argv[i]); will return 0123 because if you try to add number and string JS coerce number to string and then just concatenate them together.
sum += Number(process.argv[i]); will return 6 because Number() tries to convert string to number.
Bonus: sum +=+ process.argv[i]; will also return 6
var sum = 0;
for (var i = 2; i < process.argv.length; i++) {
// sum = sum+(process.argv[i]); this treats sum as an array and pushes (process.argv[i]); to the array
//sum += Number(process.argv[i]); Works!
//sum = sum+process.argv[i]; this treats sum as an array and pushes (process.argv[i]); to the array
sum +=+ process.argv[i]; //works!
}
console.log(sum);