In JavaScript, you can check for NaN (Not-a-Number) values using the isNaN() function or the Number.isNaN() method. Here's how to do it with examples:
Using isNaN() function:
The isNaN() function returns true if the provided value is NaN, and false if it is a valid number or can be converted to one.
javascript
// Using isNaN() function
console.log(isNaN(42)); // false (42 is a valid number)
console.log(isNaN("Hello")); // true ("Hello" cannot be converted to a number)
console.log(isNaN(NaN)); // true (NaN is not-a-number)
console.log(isNaN("42")); // false ("42" can be converted to a number)
Using Number.isNaN() method:
The Number.isNaN() method specifically checks if the provided value is NaN. It returns true if the value is NaN and false otherwise.
javascript
// Using Number.isNaN() method
console.log(Number.isNaN(42)); // false (42 is a valid number)
console.log(Number.isNaN("Hello")); // false ("Hello" is not NaN but cannot be converted to a number)
console.log(Number.isNaN(NaN)); // true (NaN is not-a-number)
console.log(Number.isNaN("42")); // false ("42" is not NaN but can be converted to a number)
The key difference between isNaN() and Number.isNaN() is that isNaN() attempts to coerce its argument to a number before checking if it's NaN, which may lead to unexpected results. Number.isNaN() only returns true if the provided value is NaN, making it a safer choice for checking NaN values in JavaScript.
Comments
Post a Comment