Understanding the Difference between isNaN() and Number.isNaN()

JavaScript provides two functions for checking whether a value is NaN, but they behave differently. Let's dive into the distinction between isNaN() and Number.isNaN():



  1. isNaN()

  • Global function
  • Returns true if the provided value cannot be converted to a number, or if it's NaN.
  • Performs type coercion, which can lead to unexpected results with non-numeric values.

isNaN(NaN);        // true
isNaN("NaN");      // true (non-numeric string)
isNaN(undefined);  // true (cannot convert undefined to a number)

        

  1. Number.isNaN():

  • Static method on the Number object
  • Returns true only if the provided value is exactly NaN.
  • Does not perform type coercion, providing precise NaN checks.

Number.isNaN(NaN);        // true
Number.isNaN("NaN");      // false (string is not NaN)
Number.isNaN(undefined);  // false (undefined is not NaN)        

?? Why does it matter? The distinction is crucial when you want to ensure precise NaN checks without unexpected type coercion. Use Number.isNaN() for that purpose.

?? Pro Tip: When working with JavaScript, understanding these nuances can save you from debugging headaches and help you write more robust code.

要查看或添加评论,请登录

Pushpendra Singh的更多文章

  • Hoisting In JavaScript

    Hoisting In JavaScript

    Hoisting :- Hoisting is a very important concept in JavaScript. This means that we can use a variable or function even…

    1 条评论

社区洞察

其他会员也浏览了