typeof 연산자

song·2023년 12월 3일
0

js 정보

목록 보기
18/30

typeof 연산자

데이터 타입을 문자열로 반환
8가지 중 하나로 반환함

  • "number"
  • "string"
  • "boolean"
  • "bigint"
  • "undefined"
  • "symbol"
  • "object"
  • "function"
// ex)
typeof ''              // "string"
typeof NaN             // "number"
typeof null            // "object"
typeof 10n 			   // "bigint"
typeof undefined       // "undefined"
typeof []              // "object"
typeof {}              // "object"
typeof new Date()      // "object"
typeof /test/gi        // "object"
typeof function () {}  // "function"


📍주의) null, undefined, 배열

null

문제
: typeof null을 하면 null이 아닌 “object”를 반환

이유
: JavaScript 초기버전 설계 오류 때문
그래서 null을 확인하기 위한 방법

let a = null;
console.log(a === null) // true
console.log(typeof a === null) // false

undefined

문제
: 선언하지 않은 식별자에게 "undefined"를 반환

// ex) apple 이라는 변수는 선언하지 않았음
console.log(typeof apple) // undefined

이유
1. 선언되지 않은 변수에 접근할 때 오류 방지
2. 호환성 및 이전 코드 지원하기 위함



배열

문제
: typeof 배열을 하면 “object”를 반환

const arr  = [1, 2, 3, 4];
console.log(typeof arr);	// object


출처

https://poiemaweb.com/js-operator

profile
인간은 적응의 동물

0개의 댓글

관련 채용 정보