I am trying to increment a variable using the ++
operator but I keep getting NaN
as a result and I'm not sure why. Here is my code:
var wordCounts = { };
var x = 0
var compare = "groove is in the heart";
var words = compare.split(/\b/);
for(var i = 1; i < words.length; i++){
if(words[i].length > 2){
wordCounts["_" + words[i]]++;
}
}
alert(wordCounts.toSource());
NaN , which stands for "Not a Number", is a value that JavaScript returns from certain functions and operations when the result should be a number, but the result is not defined or not representable as a number. For example: parseInt() returns NaN if parsing failed: parseInt('bad', 10) Math.
Nan means “Not a number”, this is because inside your cube function, you're not calling the square function, but getting it's contents. Change return x * square; with return x * square(x); and it should work.
The special value NaN shows up in JavaScript when Math functions fail ( Math. sqrt(-37) ) or when a function trying to parse a number fails ( parseInt("No integers here") ). NaN then poisons all other math functions, leading to all other math operations resulting in NaN .
The value i++ is the value of i before the increment. The value of ++i is the value of i after the increment. Example: var i = 42; alert(i++); // shows 42 alert(i); // shows 43 i = 42; alert(++i); // shows 43 alert(i); // shows 43. The i-- and --i operators works the same way.
The value of wordCounts["_" + words[i]]
is initially undefined
so when you ++ it, it gives you NaN. Just change your code to:
if (wordCounts["_" + words[i]]) {
wordCounts["_" + words[i]]++;
} else {
wordCounts["_" + words[i]] = 1;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With