How to convert NaN to 0 using JavaScript ?

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. In this article, we will convert the NaN to 0.

Using isNaN() method: The isNan() method is used to check the given number is NaN or not. If isNaN() returns true for “number” then it assigns the value 0.

  • Example:
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    <script>
        number = NaN;
        if (isNaN(number)) number = 0;
        console.log(number);
    </script>

    chevron_right

    
    

  • Output:
    0

Using || Operator: If “number” is any falsey value, it will be assigned to 0.

  • Example:
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    <script>
        number = NaN;
        number = number || 0;
        console.log(number);
    </script>

    chevron_right

    
    

  • Output:
    0

Using ternary operator: Here number is checked via ternary operator, similar to 1, if NaN it converts to 0.

  • Example:
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    <script>
        number = NaN;
        number = number ? number : 0;
        console.log(number);
    </script>

    chevron_right

    
    

  • Output:
    0

Note: While executing the code on our IDE or on your browser, check console (F12) to see the result.

full-stack-img




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.