Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Increment operator returns NaN

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());
like image 622
mcgrailm Avatar asked Nov 29 '11 05:11

mcgrailm


People also ask

Why is my function returning NaN?

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.

Why do I get NaN?

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.

Why do I get NaN in JavaScript?

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 .

What does i ++ mean in JavaScript?

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.


1 Answers

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;
}
like image 77
laurent Avatar answered Sep 19 '22 14:09

laurent