w3resource

JavaScript: isNaN() function

Description

The isNaN function is used to determine whether a value is "NaN" (not a number) or not. isNaN is a top-level function and is not associated with any object.

Syntax

isNan(testvalue)

Parameters

testvalue: The value to evaluate.

Example: isNaN() function

The following example shows how to use isNaN() function.

JavaScript Code:

console.log(isNaN("Good Morning"));
console.log(isNaN("2009/01/01"));
console.log(isNaN(455));
console.log(isNaN(-9.34));
console.log(isNaN(15-12));
console.log(isNaN(0));

View the example in the browser

Live demo:

See the Pen isnan-function-1 by w3resource (@w3resource) on CodePen.

Previous: JavaScript isFinite() function
Next: JavaScript: parseInt() function



JavaScript: Tips of the Day

JavaScript: Quick Float to Integer

If you want to convert a float to an integer, you can use Math.floor() , Math.ceil() or Math.round() . But there is also a faster way to truncate a float to an integer using |, the bitwise OR operator.

console.log(23.9 | 0);  // Result: 23
console.log(-23.9 | 0); // Result: -23

The behaviour of | varies depending on whether you're dealing with positive or negative numbers, so it's best only to use this shortcut if you're sure.
If n is positive, n | 0 effectively rounds down. If n is negative, it effectively rounds up. To put it more accurately, this operation removes whatever comes after the decimal point, truncating a float to an integer.
You can get the same rounding effect by using ~~, as above, and in fact any bitwise operator would force a float to an integer. The reasons these particular operations work is that - once forced to an integer - the value is left unchanged.

Remove Final Digits
The bitwise OR operator can also be used to remove any amount of digits from the end of an integer. This means we don't have to use code like this to convert between types:

let str = "1553"; 
Number(str.substring(0, str.length - 1));

Instead, the bitwise OR operator allows us to write:

console.log(1553 / 10   | 0)  // Result: 155
console.log(1553 / 100  | 0)  // Result: 15
console.log(1553 / 1000 | 0)  // Result: 1

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