Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When and why number evaluates to NaN, after multiplying, in Javascript?

From my experience I know, that I can get NaN when doing some division or when trying to make a number out of string, when it actually does not contain a number. Are there any other situations, when I can get a NaN. In particular -- is it possible to get it from multiplication?

This is a piece of code, that I use in my PhoneGap application:

var g = 9.80665;

acceleration.x = (acceleration.x * g).toFixed(2);
acceleration.y = (acceleration.y * g).toFixed(2);
acceleration.z = ((acceleration.z + 1) * g).toFixed(2);

An acceleration is a base PhoneGap object and I can hardly believe, that it contains a string or any other value, except float, that could result in a NaN.

However, in some certain situations (on some specific devices) I'm getting a NaN out of above.

It isn't a problem for me to "secure" above values with a code like this:

acceleration.x = (parseFloat(acceleration.x) || 0) + ' m/s\u00b2';
acceleration.y = (parseFloat(acceleration.y) || 0) + ' m/s\u00b2';
acceleration.z = (parseFloat(acceleration.z) || 0) + ' m/s\u00b2';

But, I'm really curious, when and why I can get a NaN after doing just a multiply of some values?

BTW: I've read this at MDN, as good as many related answers here at Stack Overflow, but to brought me no help or answer to my question.

like image 924
trejder Avatar asked Oct 30 '25 08:10

trejder


1 Answers

You'll get a NaN when multiplying a number with something that can't be converted to a number.

1 * '100'         // 100 because '100' will be converted to 100
1 * ''            // 0 because '' will be converted to 0
1 * 'ten'         // NaN because 'ten' can't be converted to a number
1 * []            // 0 because [] converted to number will be 0
1 * [123]         // 123 because [] will be 123
1 * ['ten']       // NaN
1 * {}            // NaN
1 * true          // 1 because true will be 1
1 * false         // 0
1 * null          // 0
1 * undefined     // NaN, undefined can't be converted to number
1 * function(){}  // NaN

The function 'isNaN' checks if the expression can be converted to a number o not. You culd check both numbers of the multiplication to confirm that both are numbers to avoid errors.

For the sake of completeness, to know if a variable is exactly NaN you must compare it with itself:

var a = NaN;
if (a != a) console.log('a is NaN');

It happens because NaN is defined to be unequal to everything, including itself.

like image 72
Kaizo Avatar answered Oct 31 '25 20:10

Kaizo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!