[JS] undefined, null, NaN, Infinity 의미

2020. 6. 8. 18:44Javascript

undefined

- 정의 및 초기화 되지 않은 변수의 자료형 (전역객체 식별자 역할)
- 매개변수에 대응되는 값을 할당받지 못할 때, function과 statement에서 반환되는 자료형

null

- null이 할당된 변수가 어떤 객체도 가리키지 않는다는 의미

typeof null          // "object" (하위호환 유지를 위해 "null"이 아님)
typeof undefined     // "undefined"

NaN

- Not a Number의 약자
- 자료형은 Number이지만, 컴퓨터로 표현할 수 없는 수치형 결과
즉, 수식의 결과가 숫자가 아니면 NaN을 반환된다.

0/0             // NaN
"Hello"*1000    // NaN
Math.sqrt(-3)   // NaN

그렇다면 아래의 코드를 실행하면 'result of expression:: NaN'이 출력될까?

expression = 0/0;

if ( expression == NaN ){
	console.log('result of expression:: NaN');
}

아니다, NaN 자료형은 자신과도 일치하지 않다. NaN의 자료형은 Number이기 때문에, NaN이라해도 0/0과 sqrt(-3)의 결과값이 다르다. 그렇다면 어떻게 해야할까?

expression = 0/0;

if ( isNaN(expression) ){
	console.log('result of expression:: NaN');
}

isNaN()를 이용해서 boolean형태로 결과값을 반환받을 수 있다. 하지만 10/0을 했을 경우 NaN이 아닌 Infinity가 나온다. 이건 무엇일까?

Infinity / -Infinity

- 부동 소수점 숫자 한계를 넘어가는 숫자

Infinity -1.797xxxxxxxxxxxxxxxxxxx+10308
Infinity1.797xxxxxxxxxxxxxxxxxxx+10308)

'Javascript' 카테고리의 다른 글

sort 함수 커스터마이징  (0) 2020.09.12
[JS] 프로토타입  (0) 2020.06.17
[JS] ||, && 연산자 사용  (0) 2020.06.08