티스토리 뷰

반응형
  • 변수 할당에서도 &&와 ||를 유용하게 사용할 수 있다.

&&(AND)

  • const temp = a && b : a가 있으면 b를 쓴다.
let a;
/* 
let a = undefined; // undefined가 출력된다.
let a = null; // null이 출력된다.
let a = ''; // 빈 문자열이 출력된다.
let a = 0; // 0이 출력된다.
let a = false; // false가 출력된다.
*/

const temp1 = a && 'ingnoh';
console.log(temp1); // undefined가 출력된다.

a = 'monkey';
const temp2 = a && 'ingnoh';
console.log(temp2); // ingnoh가 출력된다.

||(OR)

  • const temp = a || b : a가 없으면 b를 쓴다.
let a;
// 아래는 모두 ingnoh가 출력된다. a가 없는 것으로 취급됨!
// let a = undefined;
// let a = null;
// let a = '';
// let a = 0;
// let a = false;
const temp1 = a || 'ingnoh';
console.log(temp1);

a = 'monkey';
const temp2 = a || 'ingnoh';
console.log(temp2);

응용

  • const temp = a && (b || c) : a가 있으면, b가 있으면 b를 쓰고 없으면 c로 초기화한다.
const obj = {
    hello: {
        world: 1
    },
    monkey: {
        
    }
}
console.log(obj.hello && (obj.hello.world || null)); // 1이 출력된다.

console.log(obj.ingnoh && (obj.hello.world || null)); // undefined가 출력된다.

console.log(obj.monkey && (obj.monkey.world || null)); // null이 출력된다.

 

댓글
반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
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 31
글 보관함