반응형
이 개념에 대해 알고 있으면 정말 유용해서 정리한다.
초급개발자인 나도 여전히 헷갈리니깐 정리해두는 것!
Truthy: true 같은거! Falsy: False 같은거!
아래 5가지는 꼭 외우기
1. undefined
2. null
3. 0
4. ''
5. Nan
예를 들어, 아래와 같은 코드가 있을 경우 undefined는 걸러낼 수 있지만, null이 전달 될 경우 ?
function print(person) {
if(person === undefined){
return;
}
console.log(person.name);
}
const person = null;
print();
그럼 아래와 같이 조건을 또 추가해줘야한다.
function print(person) {
if(person === undefined || person === null){
return;
}
console.log(person.name);
}
const person = null;
print();
위 두가지를 간단하게 표현하려면 아래와 같이 가능하다.
** 현재 person은 null로 falsy한 값이다. !를 붙여줘서 truthy한 값으로 변경해주는것!
function print(person) {
if(!person){
return;
}
console.log(person.name);
}
const person = null;
print(person);
아래 5가지 값에 !를 붙여 줄 경우 Falsy => Truthy한 값으로 바뀐다.
!undefined
!null
!0
!''
!Nan
아래 값에 !붙일 경우 Truthy => Falsy로 변경
!3
!'hello'
!['array']
![]
!{ value:3 }
반응형
'JS' 카테고리의 다른 글
웹서버란? (Web-Server) (0) | 2023.09.06 |
---|---|
[DeepDive] 변수 선언, 할당, 초기화, 호이스팅? (0) | 2022.02.18 |
[알고있으면 유용한 자바스크립트 문법] 삼항연산자 (0) | 2022.01.30 |