[javascript] isNaN() vs Nember.isNaN() 뿌시기

yoon-bomi·2022년 8월 11일
0
post-thumbnail

isNaN() 을 설명한 공식문서를 보면 이런 내용이 적혀있다.

isNaN() 함수는 어떤 값이 NaN인지 판별합니다. isNaN 함수는 몇몇 혼란스러운 케이스을 가지고 있으므로, ECMAScript 2015에서 추가한 Number.isNaN()으로 바꾸는 편이 좋을 수도 있습니다.

isNaN()Nember.isNaN() 는 어떻게 다를까? 🤔


isNaN() vs Nember.isNaN()

아래 간단한 예시를 보자.

isNaN("blabla") // true
Nuber.isNaN("blabla") // false

isNaN(NaN) // true
Nuber.isNaN(NaN) // true

분명 같은 string 값을 넣었는데 다른 결과가 도출된다.

why?

isNaN 을 직역하면 이 값이 NaN 이니? 이다.

하지만 isNaN()매개변수의 값을 강제로 Number 로 캐스팅 하기 때문에 Numer("blabla") = NaN 이 되고, isNaN(NaN) = true 라는 값이 도출 되는 것이다.

isNaN("blabla") = isNaN(Number("blabla")); // 강제로 Number 캐스팅
Number("blabla") = NaN

isNaN("blabla") // true

"blabla" !== NaN 임에도 불구하고 isNaN("blabla") = true 라는 결과가 도출되기 때문에, 사이드 이펙트가 발생할 수도 있어서 온전히 NaN 일 때만 true 를 반환하는 Number.isNaN() 을 사용하라는 의미인 것으로 추측된다. (내 생각)

Number.isNaN("blabla") // false
Number.isNaN("1234") // false
Number.isNaN("1234ABC") // fasle
Number.isNaN(1234) // false

Number.isNaN(NaN) // true

typescript 에서 isNaN() 을 사용할 때 문제점

공식 문서에서도 isNaN() 이 아닌 Number.isNaN() 사용을 권장하고 있다.
자바스크립트는 타입에 대한 정의가 없어서 에러가 나지 않지만 타입스크립트에서 isNaN() 의 매개변수로 number 타입만 받을 수 있어서, string 타입을 넣을 경우 타입 에러가 발생한다.

하지만 Number.isNaN() 는 매개변수를 unknown 타입으로 받기 때문에 string 타입이 들어가도 타입 에러가 발생하지 않는다.

 // Argument of type 'string' is not assignable to parameter of type 'number'. ts(2345)
  if (isNaN('string')) { // type error 발생
    console.log('value is NaN 😕');
  }


  if (Number.isNaN('string')) { // false
    console.log('value is NaN 😕');
  }

결론

isNaN = function(value) {
    Number.isNaN(Number(value));
}

특별한 이유가 없다면 정확한 판단을 위해 isNaN(value) 대신 Number.isNaN(value) 를 사용하자!



ref.
공식 문서 https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN

profile
웹 풀스택에서 백엔드로 진화중 🧚🏻‍♀️

0개의 댓글