[모던자바스크립트] 알고 있으면 유용한 자바스크립트 문법 - 연산자, 조건문

고민경·2023년 7월 11일

삼항 연산자

삼항 연산자의 사용법은 다음과 같다
조건 ? true일 때 : false일 때

const array = [];
let text = array.length === 0 ? '배열이 비어있습니다' : '비어있지 않습니다'

console.log(text);

Truthy and Falsy

Truthy(참 같은 값)와 Falsy(거짓 같은 값)는 boolean 타입의 구문에서 JavaScript의 값이 true나 false로 평가되는 것을 뜻한다.
다음 예시에서, 어떤 함수 print의 파라미터 person이 undefined이거나 null인 상황을 대비하려면 아래와 같이 코드를 작성해야 한다.

function print(person) {
  if (person === undefined || person === null) {
    console.log('person이 없네요');
    return;
  }
  console.log(person.name);
}

const person = null;
print(person);  // person이 없네요

위 코드를 다음과 같이 축약해서 작성할 수 있다.

function print(person) {
  if (!person) {
    console.log('person이 없네요');
    return;
  }
  console.log(person.name);
}

const person = null;
print(person);

이렇게 작동하는 이유는 undefined와 null은 Falsy한 값이기 때문이다. Falsy한 값 앞에 느낌표를 붙여주면 true로 전환된다.

console.log(!undefined);	// true
console.log(!null);			// true
console.log(!0);			// true
console.log(!'');			// true
console.log(!NaN);			// true

undefined, null, 0, '', NaN은 모두 Falsy한 값이다. 그 외의 값은 모두 Truthy한 값이다.

console.log(!3);			// false
console.log(!'hello');		// false
console.log(!['array?']);	// false
console.log(![]);			// false
console.log(!{ value: 1 });	// false

if문에서 Truthy 값과 Falsy 값을 활용하면 편하다.

const value = { a: 1};
if (value) {
  console.log('value가 Truthy 하네요.');  // value가 Truthy 하네요. 
}

valuerk Truthy한 값이기 때문에 콘솔에 메시지가 출력된다. 반면에 value가 null, undefined, 0, '', NaN 중 하나라면 메시지가 출력되지 않는다.

💡 Tip
만약에 특정 값이 Truthy한 값이라면 true, 그렇지 않다면 false로 값을 표현하고자 할 때 삼항 연산자를 사용하여 다음과 같이 작성할 수 있다.

const value = { a: 1 };
const truthy = value ? true : false;

더 쉽게 작성하는 것도 가능하다.

const value = { a : 1 };
const truthy = !!value;

!value는 false가 되고, 여기에 !false는 true가 되어서, 결과는 true가 된다.

논리 연산자를 사용한 단축 평가

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

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

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

let name = getName();
console.log(name);  // undefined

name = getName(dog);
console.log(name);  // 멍멍이

위의 함수가 작동하는 이유는 A && B 연산자를 사용하게 될 때 A가 Truthy한 값이라면, B가 결과값이 된다. 반면, A가 Falsy한 값이라면 결과는 A가 된다. 특정 값이 유효할 때에만 어떤 값을 조회하는 작업을 해야할 때 이러한 속성을 이용하면 매우 유용하다.

console.log(true && 'hello'); // hello
console.log(false && 'hello'); // false
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

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

|| 연산자는 만약 어떤 값이 Falsy 하다면 대체할 값을 지정해줄 때 유용하게 사용할 수 있다. A || B는 만약 A가 Truth 할 경우 결과는 A가 된다. 반면, A가 Falsy 하다면 결과는 B가 된다.

const namelessDog = {
  name: ''
};

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

const name = getName(namelessDog);
console.log(name);  // 이름이 없는 동물입니다.

조건문 더 스마트하게 쓰기

<특정 값이 여러 값 중 하나인지 확인해야 할 때>

1. 연산자 사용
비교해야 할 값이 많아질수록 코드는 길어진다.

function isAnimal(text) {
  return (
    text === '고양이' || text === '개' || text === '거북이' || text === '너구리'
  );
}

console.log(isAnimal('개')); // true
console.log(isAnimal('노트북')); // false

2. 배열을 만들고 배열의 includes 함수 사용

function isAnimal(name) {
  const animals = ['고양이', '개', '거북이', '너구리'];
  return animals.includes(name);
}

console.log(isAnimal('개')); // true
console.log(isAnimal('노트북')); // false

animals 배열을 선언하는 것도 생략하고 화살표 함수로 작성할 수도 있다

const isAnimal = name => ['고양이', '개', '거북이', '너구리'].includes(name);
console.log(isAnimal('개')); // true
console.log(isAnimal('노트북')); // false

<값에 따라 다른 결과물을 반환해야 할 때>

동물 이름을 받아오면 동물의 소리를 반환하는 함수를 만든다고 가정하면,
1. if문 사용

function getSound(animal) {
  if (animal === '개') return '멍멍!';
  if (animal === '고양이') return '야옹~';
  if (animal === '참새') return '짹짹';
  if (animal === '비둘기') return '구구 구 구';
  return '...?';
}

console.log(getSound('개')); // 멍멍!
console.log(getSound('비둘기')); // 구구 구 구
console.log(getSound('노트북')); // ...?

2. switch case 사용
switch문에서 return을 할 때는 break를 생략해도 된다.

function getSound(animal) {
  switch (animal) {
    case '개':
      return '멍멍!';
    case '고양이':
      return '야옹~';
    case '참새':
      return '짹짹';
    case '비둘기':
      return '구구 구 구';
    default:
      return '...?';
  }
}

console.log(getSound('개')); // 멍멍!
console.log(getSound('비둘기')); // 구구 구 구
console.log(getSound('노트북')); // ...?

3. 객체 사용
특정 값에 따라 반환해야 하는 값의 조건이 여러 가지 있을 때는 객체를 활용하면 좋다.

function getSound(animal) {
  const sounds = {: '멍멍!',
    고양이: '야옹~',
    참새: '짹짹',
    비둘기: '구구 구 구'
  };
  return sounds[animal] || '...?';
}

console.log(getSound('개')); // 멍멍!
console.log(getSound('비둘기')); // 구구 구 구
console.log(getSound('노트북')); // ...?

4. 객체에 함수를 넣기
값에 따라 실행해야 하는 코드 구문이 다를 때는 객체에 함수를 넣으면 된다.

function makeSound(animal) {
  const tasks = {
    () {
      console.log('멍멍');
    },
    고양이() {
      console.log('고양이');
    },
    비둘기() {
      console.log('구구 구 구');
    }
  };
  if (!tasks[animal]) {
    console.log('...?');
    return;
  }
  tasks[animal]();
}

makeSound('개'); // 멍멍!
makeSound('비둘기'); // 구구 구 구
makeSound('노트북'); // ...?

0개의 댓글