: JS는 동적인 타입을 가지는 언어이므로 타입 검사가 어렵습니다. 타입을 체크할 수 있는 여러 방법을 소개합니다.
typeof Something : returns string(string, boolean, number, object, function, undefined, symbol)
typeof로 PRIMITIVE value를 체크할 경우 본래 타입으로 리턴되나, REFERENCE value 경우 다르게 리턴될 수 있으므로 유의해야 합니다.
동적인 타입까지 검사하기 어렵습니다.
객체의 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 👍
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이기 때문
: 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]' 👍
!null (flip value) // returns true
!!null (boolean으로 형변환) // returns false
null === false // returns false
!null === true // returns true
null + 123 // returns 123 (수학적으로 null = 0)
// 선언했지만 값은 정의되지 않고 할당되지 않은 상태
let varb;
varb // returns 'undefined'
undefined + 10 // returns NaN
!undefined // returns true
undefined === null // returns false
!undefined === !null // returns true
undefined, null : 값이 없거나 정의되지 않은 값.
숫자로는,
타입은,
: 동등 연산자(==)
: 형변환이 일어나므로 위험합니다.
'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
표시되는 닉네임 바꾸셨나보군요.
오랜만에 들렀다가요. 글 잘 보고 갑니다.