Getting NaN Instead of Number

2.9k views Asked by At

I am having a small problem with the code below, instead of a number I am getting NaN. What's wrong?

for (var i = 0; i<100; i++) {
    x = i ^ i
    result = x + result;
}
var y = result - (result ^ result);
console.log(y);
2

There are 2 answers

0
Lajos Arpad On BEST ANSWER

It was NaN because you did not initialize result at the start.

Let us see the script:

var result = 0;
var x;
for (var i = 0; i<100; i++) {
    x = i ^ i
    result = x + result;
}

Here you are running the bitwise XOR for each i. Since all the bits in i are equal to themselves, x will always be 0. result is 0 at the start and each time you add 0 to it, so as a result, at the end the value of result is 0.

var z = result ^ result;

When you are XOR-ing result with itself, then, again, all bits of result are equal to themselves, so the result will be 0.

var y = result - z;

You are subtracting 0 from 0, resulting in 0.

A XOR B = A <> B

In bitwise level

A XOR B results in the result of the XOR on each bit.

0
Schism On

To be a bit more specific on why you got NaN: as @LajosArpad said, you're effectively just doing result = 0 + result; 100 times.

However, since you didn't initialise result, it was undefined. Mathematical operations (such as 0 +) on undefined will always result in NaN.