Javascript

javascript - 단축 평가 논리 계산법(Short-circuit evaluation)

Starters 2020. 9. 4. 20:43

단축 평가 논리 계산법(Short-circuit evaluation)

- 논리연산자를 사용해서 코드를 더 짧게 쓰는 법을 말한다.

 

조건문 예시

const dog = {
  name = '멍멍이';
}

function getName(animal){
  if(animal) {
    return animal.name;
  }
  return undefined;
}

const name = getName();
console.log(name);

 

 짧은 코드로

const dog = {
  name = '멍멍이';
}

function getName(animal){
  return animal && animal.name;
}

const name = getName();
console.log(name);

 

왜 이게 가능하지?

And (&&) 연산자

console.log(true && 'hello') 를 하면 연산 결과는 'hello'가 된다.

console.log(false && 'hello') 를 하면 앞에 false가 왔기 때문에 뒤에 값은 보지도 않음

console.log('hello' && 'bye') 는 'hello'가 truthy한 값이기 때문에 'bye'가 결과로 나옴

console.log(null && 'hello') 는 null이 falsy한 값이기 때문에 결과는 null

console.log(undefined && 'hello') undefined이 falsy한 값이기 때문에 결과는 undefined

console.log('' && 'hello') => ""

console.log(0 && 'hello') => 0

console.log(1 && 'hello') => 'hello'

console.log(1 && 1) => 1

 

==> && 연산자는 앞에 오는 값에 따라 결과값이 달라진다.

 

Ex)

const object = { name : 1 }; // 만약 이 값이 객체일 수도 있지만 객체가 아닐 수도 있다면,

// const name = object.name; // 이거 대신에
const name = object && object.name; // 이렇게 쓰면 오류없이 사용할 수 있다.
console.log(name)

 

Or (&&) 연산자

일반 조건문

const namelessDog = {
	name : '',
};

function getName(animal) {
	const name = animal && animal.name;
    if(!name){
    	return '이름이 없는 동물입니다.';
    }
    return name;
}

const name = getName(namelessDog);
console.log(name);

코드 짧게

const namelessDog = {
	name : '',
};

function getName(animal) {
	const name = animal && animal.name;
    return name || '이름이 없는 동물입니다.';
}

const name = getName(namelessDog);
console.log(name);

왜 그러지?

console.log(false || 'hello'); => 'hello' // 앞의 값이 falsy한 값이 거나 false이면 뒤에 값이 결과값이 된다.

console.log('' || 'hello');

console.log(null || 'hello');

console.log(undefined || 'hello');

console.log(0 || 'hello');

 

앞의 값이 true이거나 truthy한 값이라면

console.log(1 || 'hello'); => 1 // 뒤에 값은 보지도 않는다.

console.log(true || 'hello');

console.log('와아' || 'hello');

console.log([ ] || 'hello');