[클린코드 자바스크립트] Type 다루기

Ina·2022년 4월 4일
1

Javascript

목록 보기
1/3

Javascript 타입 검사 방법

: JS는 동적인 타입을 가지는 언어이므로 타입 검사가 어렵습니다. 타입을 체크할 수 있는 여러 방법을 소개합니다.

typeof Something : returns string(string, boolean, number, object, function, undefined, symbol)

1. typeof 연산자

PRIMITIVE vs REFERENCE

typeof로 PRIMITIVE value를 체크할 경우 본래 타입으로 리턴되나, REFERENCE value 경우 다르게 리턴될 수 있으므로 유의해야 합니다.

  • typeof aFunction : returns 'function' 👍
  • typeof class : returns 'function' 👍
  • typeof new String : returns 'object' 😰
  • typeof null : returns 'object' (JS의 언어적인 오류) 😱

JS는 동적타입 언어

동적인 타입까지 검사하기 어렵습니다.

2. instanceof

객체의 property type 체크하는 연산자

function Person(name, age) {
	this.name = name;
    this.age = age;
}
    
const coco = new Person('CoCo', 99)
coco instanceof Person  // returns true 👍

const lili = {
	name : 'coco',
    age : 99
}

lili instanceof Person // returns false 👍

instanceof 사용시 주의

const arr = []
const func = function() {
	do something..	
}
const date = new Date()
arr instanceof Array  // returns true 👍
func instanceof Function  // returns true  👍
date instanceof Date  // returns true  👍

arr instanceof Object  // returns true 😰
func instanceof Object  // returns true  😰
date instanceof Object  // returns true  😰
// ---> Array, Function, Date 타입 모두 최상위는 Object이기 때문

3. Object.prototype.toString.call('')

: reference 객체 최상위는 Object라는 점을 역이용하여 타입을 체크하는 유용한 방법입니다.

Object.prototype.toString.call(new String(''))  // returns '[object String]' 👍
Object.prototype.toString.call(arr)  // returns '[object Array]' 👍
Object.prototype.toString.call(func)  // returns '[object Function]' 👍
Object.prototype.toString.call(date)  // returns '[object Date]' 👍

undefined & null

null - 혼란하다 혼란해..

!null (flip value) // returns true
!!null (boolean으로 형변환) // returns false

null === false // returns false

!null === true // returns true

null + 123 // returns 123 (수학적으로 null = 0)

undefined - 혼란하다 혼란해..

// 선언했지만 값은 정의되지 않고 할당되지 않은 상태
let varb;

varb // returns 'undefined'

undefined + 10 // returns NaN

!undefined // returns true
undefined === null  // returns false
!undefined === !null  // returns true

나름대로 정리를 해보자면,

undefined, null : 값이 없거나 정의되지 않은 값.

숫자로는,

  • undefined : 수학적으로 NaN
  • null : 수학적으로 0

타입은,

  • undefined : undefined 타입
  • null : Object 타입

eqeq 줄이기

: 동등 연산자(==)

동등 연산자(==)

: 형변환이 일어나므로 위험합니다.

'1' == 1 // returns true
1 == true // returns true

ex. id ticketNum 인풋창에 0이 입력되어 있는 경우

const ticketNum = $('#ticketNum')
ticketNum.value // returns '0'
ticketNum.value === 0 // returns false (type이 서로 다르기 때문에 false 🥲)

// 때문에 아래처럼 일부러 느슨한 검사를 역이용하기도 하는데, 협업할 때 팀원들이 헷갈릴 수 있습니다.
ticketNum.value == 0 // returns true 
// 안전하게 재작성하려면,
// 강제로 type을 비교하고자 하는 값과 일치시킨 후
// strict equality 체크를 해줍니다. 👍

Number(ticketNum.value) === 0
profile
프론트엔드 개발자. 기록하기, 요가, 등산

1개의 댓글

comment-user-thumbnail
2022년 5월 10일

표시되는 닉네임 바꾸셨나보군요.
오랜만에 들렀다가요. 글 잘 보고 갑니다.

답글 달기