728x90

논리 연산자를 효율적으로 사용하는 방법이라고 보면 된다.

 

console.log(true && "hello"); // 'hello'
console.log(null && undefined); // null
console.log(undefined && "hello"); // undefined
console.log("hello" && null); // null
console.log("hello" && "bye"); // bye
console.log(null && "hello"); // null
console.log(undefined && "hello"); // undefined
console.log('' && 'hello'); // ''
console.log(0 && 'hello'); // 0
console.log(1 && 'hello'); // hello
console.log(1 && 1); // 1

&& 연산자는 첫번째가 true 이면 뒤에 있는 hello 를 반환한다.

첫번째가 false 이면 첫번째를 반환한다.

 

&& 연산자로 코드 단축시키기

const seaFood = {
  name"쭈꾸미"
}
 
function getName(fish) {
  // && 논리 연산자가 truly 하면 fish.name 을 반환한다.
  return fish && fish.name
}
 
const name = getName(seaFood);
console.log(name); // '쭈꾸미'

fish 도 Truthy 하고 fish.name 또한 Truthy 하다면 오른쪽의 값을 return 한다.

 

|| 연산자로 코드 단축시키기

A || B 는 만약 A 가 Truthy 할경우 결과는 A 가 됩니다. 반면, A 가 Falsy 하다면 결과는 B 가 된다.

const seaFood = {
  name"박달대게"
};
 
function getName(fish) {
  // fish 가 Truthy 하면 왼쪽 값인 fish 를 return 
  // fish 가 Falsy 하면 오른쪽 값인 '이름없음' 을 return
  return fish || '이름없음'
}
 
const name = getName(seaFood)
console.log(name// {name : 박달대게}
 
const name2 = getName()
console.log(name2) // '이름없음'
 

 

 

블로그 이미지

Link2Me

,