w3resource

JavaScript: NaN

Description

NaN is a value represents not a number.

NaN is a top level property and is not associated with any object.

NaN is never equal to any other number, including NaN itself. It is not possible to check whether a value is a number by comparing it with NaN using equal to operator. You have to use the isNaN function instead.

Methods like Number constructor, parseFloat, and parseInt return NaN if the argument passed to them are not numbers.

NaN property can be used to refer an error for a function, provided the function returns a valid number.

Syntax

NaN

Example of JavaScript NAN - when math function fails

JavaScript Code:

console.log(Math.abs('MyString'));

View example of JavaScript NAN - when math function fails

Live demo:

See the Pen nan-property-1 by w3resource (@w3resource) on CodePen.


JavaScript Code:

console.log(parseInt("xyz"));

View Example JavaScript NAN - when a function tries to read a number fails

Live demo:

See the Pen nan-property-2 by w3resource (@w3resource) on CodePen.


Note

Since Equality operator (i.e. == and ===) cannot be used to test a value against NaN, If you wish to perform such a test, use isNAN instead of NAN.

See the Pen javascript-common-editor by w3resource (@w3resource) on CodePen.

Previous: JavaScript: parseFloat() function
Next: JavaScript: Number functionJavaScript: Number function



JavaScript: Tips of the Day

semicolon (;)

function nums(a, b) {
  if (a > b) console.log('a is bigger');
  else console.log('b is bigger');
  return;
  a + b;
}

console.log(nums(4, 2));
console.log(nums(1, 2));

In JavaScript, we don't have to write the semicolon (;) explicitly, however the JavaScript engine still adds them after statements. This is called Automatic Semicolon Insertion. A statement can for example be variables, or keywords like throw, return, break, etc.
Here, we wrote a return statement, and another value a + b on a new line. However, since it's a new line, the engine doesn't know that it's actually the value that we wanted to return. Instead, it automatically added a semicolon after return. You could see this as:

return;
a + b;
This means that a + b is never reached, since a function stops running after the return keyword. If no value gets returned, like here, the function returns undefined. Note that there is no automatic insertion after if/else statements!

Ref: https://bit.ly/3jFRBje