티스토리 뷰
728x90
반응형
Truthy : 값이 존재한다.
// truthy
console.log(!3); // false
console.log(!"hello"); // false
console.log(![]); // false
console.log(!{}); // false
Falsy: 값이 존재하지 않거나, 비어있는 것
- undefined
- null
- 0
- "" , '' (비어있는 문자열)
- NaN (Not a Number)
// falsy
console.log(!undefined); //true
console.log(!null); //true
console.log(!0); //true
console.log(!""); //true
console.log(!NaN); //true (NaN: Not a Number)
특히 아래 코드의 if (person === undefined || person === null ) 구문에서
객체가 존재성여부 확인(undefined 체킹)을 하거나 null 여부를 직접 확인하는 코드는 좋지 않다.
console.clear();
function print(person) {
// 직접 null과 undefined checking은 좋지 않은 코드이다.
// person이 존재하지 않거나 null인경우
if (person === undefined || person === null) {
console.log("없음.");
return;
}
console.log(person.name);
}
const person = {
name: "John"
};
print(person); //John
// person 정의하지 않았음. (undefined)
print(); // 없음
// person 이 null 이라면
print(null); // 없음
undefined / null / 0 / '' / NaN 은 falsy한 값으로 정의되어 있으므로
! 하나만으로도 여러개의 falsy한 값인지 아닌지를 체킹이 가능하다.
console.clear();
function print(person) {
if (!person) {
console.log("없음.");
return;
}
console.log(person.name);
}
const person = {
name: "John"
};
print(person); //John
// person 정의하지 않았음. (undefined)
print(); // 없음
// person 이 null 이라면
print(null); // 없음
if 문으로 truthy와 falsy를 판단할 수 있다.
function func1(value) {
if (value) {
return "truthy";
}
return "falsy";
}
let value = null;
console.log(func1(value)); // falsy
value = { name: "a" };
console.log(func1(value)); // truthy
삼항연산자로도 truthy와 falsy를 판단할 수 있다
let value = null;
const isTruthy = value ? true : false ;
console.log(isTruthy); // false
그러나, 아까전에 말한것대로 ! 만으로도 truthy와 falsy를 구분할 수 있다.
let value = null;
const isTruthy = !!value;
console.log(isTruthy); // false
value = null 이라면
!value => true
!!value => !true => false
728x90
반응형
'Backend > Typescript & Angular' 카테고리의 다른 글
함수의 기본 파라미터 (0) | 2021.09.26 |
---|---|
단축평가 논리 계산법 (0) | 2021.09.26 |
삼항연산자 (0) | 2021.09.26 |
프로토타입과 클래스 (0) | 2021.09.09 |
배열 내장함수 reduce (0) | 2021.09.06 |
반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- 미완
- MongoDB
- jest
- Nest.js
- node.js
- 한달어스
- Jekyll
- 바이트디그리
- nestjs jest
- 습관개선
- 스마트폰중독
- Mongoose
- git
- nestjs
- TDD
- RDBMS
- 나도 할 수 있다
- 클린아키텍쳐
- 개발용어
- 참고
- 디지털디톡스
- gem
- OS
- MySQL
- TypeScript
- 한달독서
- 갓생살자
- typeORM
- IT용어
- vscode
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | 6 | |
7 | 8 | 9 | 10 | 11 | 12 | 13 |
14 | 15 | 16 | 17 | 18 | 19 | 20 |
21 | 22 | 23 | 24 | 25 | 26 | 27 |
28 | 29 | 30 |
글 보관함