NaN (Not a Number) is usually used to indicate an error condition for a function that should return a valid number but it can be converted to 0 using JavaScript. We will discuss how to convert the NaN to 0.
Below are the approaches used to convert NaN to 0 using JavaScript:
Table of Content
Using isNaN() method
The isNan() method is used to check whether the given number is NaN or not. If isNaN() returns true for "number" then it assigns the value 0.
Example: In this example, we will check given number is NaN or not.
number = NaN;
if (isNaN(number)) number = 0;
console.log(number);
Output
0
Using || Operator
If "number" is any falsy value, it will be assigned to 0.
Example: In this example, we will compare NaN with 0 using || operator
number = NaN;
number = number || 0;
console.log(number);
Output
0
Using ternary operator
Here the number is checked via ternary operator, similar to 1, if NaN it converts to 0.
Example: In this example, we will use the ternary operator to convert NaN to 0.
number = NaN;
number = number ? number : 0;
console.log(number);
Output
0
Note: While executing the code on our IDE or on your browser, check the console (F12) to see the result.
Using Strictly Equality(===) operator
JavaScript Strict Equality Operator is used to compare two operands and return true if both the value and type of operands are the same. to convert NaN into zero using the === operator first comparing NaN value with zero if the comparison is successful NaN is returned, otherwise, zero is returned.
Syntax:
(NaN === 0) ? NaN : 0Example: In this example, we will convert NaN to 0 by using === operator, first we compare the NaN value with zero if it is true we return NaN in another case we return 0.
let a = NaN;
a = (a === 0) ? a : 0;
console.log("Result: " + a);
Output
Result: 0
Using the Double Tilde (~~) Operator
You can use the double tilde (~~) operator in JavaScript to convert NaN to 0. The double tilde is a bitwise operator that performs a bitwise NOT operation twice, effectively converting non-numeric values to 0.
Example: In this example, the variable value is assigned the value NaN. The ~~ operator is then used to convert NaN to 0, and the result is stored in the variable result. Finally, the console.log statement prints the result, which will be 0.
let value = NaN;
let result = ~~value;
console.log(result); // Output: 0
Output
0