typeof 연산자를 사용하여 값의 타입을 확인하는 방법

ASOpaper·2022년 10월 21일
1

Javascript

목록 보기
1/11

typeof

typeof
값의 타입을 확인할 수 있는 연산자

개발자 도구를 통해 값 확인하기

console.log(typeof string) // undefined
console.log(typeof number) // undefined
console.log(typeof boolean) // undefined
console.log(typeof undefined) // undefined
console.log(typeof object) // undefined
console.log(typeof null) // object
console.log(typeof "1") // string
console.log(typeof 1) // number
console.log(typeof 1 === 1) // false
console.log(typeof 1 < 2) // false
console.log(typeof true) // boolean
console.log(typeof [1, 2, 3]) // object
console.log(typeof {name : 'Steve', age : 32, isStudent : true}) // object
console.log(typeof (1 < 2)) // boolean
console.log(typeof 8 - 3) // NaN : not a number

let num = 1
console.log(typeof num) // number
let number = "1";
console.log(typeof number) // string

확인할 점

1 === 1, typeof 1 < 2을 입력하였을 때 값이 false가 나온다는 것과 값이 지정되지 않은 단어를 사용하였을 때 undefined가 나온다는 것(할당되지 않음)이다.
또한 배열([1, 2, 3]), 객체{name : 'Steve', age : 32, isStudent : true}, null의 값은 object로 표기된다.

디스코드로 얻은 답변, typeof 1 < 2에서는 괄호가 없으므로 typeof 1이 먼저 실행돼서 num이라는 타입과 숫자 2 비교가 되는데 num 타입과 숫자 2는 비교할 수 없기 때문에 false처리가 된다고 한다.
typeof 연산자가 사칙연산자보다 우선순위가 높기 때문이고, 괄호(())를 이용해 우선순위를 표시해야 한다.
즉, true 값을 얻으려면 typeof (1 < 2) 해당 방식으로 처리하여야 한다.
또한 typeof (1 < 2)으로 처리하면 true값이 나오기 때문에 typeof에 따라 나오는 값은 boolean이다.

답변주신 내용
1. 부등호는 number 타입끼리 비교를 할 때 사용하는 연산자입니다.
숫자 타입이 아닌 것과 비교를 하면 자연스럽게 false가 출력된다고 생각하시면 될 것 같습니다.
2. 숫자 string은 자동으로 형변환해서 연산을 진행하여 정상적인 값이 나온다. > 해당 부분은 자바스크립트의 특징이다.
3. 기본적으로 String to Number 비교에서 String 타입의 값은 Number 타입으로 변환이 되는데, 문자만 표시된 String을 Number로 변환하려고 하는 경우에는 NaN 값이 됩니다.
4. typeof 1 <2 경우 typeof 1이 먼저 평가되서 'number'가 되고 그 다음 'number' < 2가 되는 데 이때, 'number'인 string과 2인 number 타입을 비교하면서 string 타입을 Number 타입으로 변환하는 것같습니다. 그러나 'number'라는 문자를 Number로 변경하면 NaN이 되기 때문에 무조곤 비교시 false 가 나오는 것 같아요. 아래는 스택플로우에는 NaN은 항상 false를 반환한다고 하네요.

Number('test'); // NaN
Number('1'); // 1

참고할자료
NaN에 대하여, Greater than (>), 연산자 우선순위, typeof에대한 MDN

**참고자료**
코드스테이츠,
http://www.tcpschool.com/
profile
개인 공부 일지

0개의 댓글