본문 바로가기

웹/JavaScript

[JS] 15. 응용: 조건문 업그레이드 방법

조건문을 더 간결하고 효율적으로 작성할 수 있는 방법 중 가장 기본적인 두 가지 방법을 알아보겠습니다.

 


① 배열 내장함수 includes 이용

 

조건문의 조건식이 여러가지 케이스 중 하나에 해당하는지를 비교하는 경우일 때 배열 내장함수 includes를 이용하는 방법입니다. 

 

 

[예시 코드]

 

/* 태극기에 사용되는 색상인지를 검사 */

function isTaegeukgiColor(color) {
  if (
    color == "white" ||
    color == "black" ||
    color == "red" ||
    color == "blue"
  ) {
    return true;
  }
  return false;
}

const color1 = isTaegeukgiColor("red");
const color2 = isTaegeukgiColor("yellow");

console.log(color1);   //true
console.log(color2);   //flase

/* 태극기에 사용되는 색상인지를 검사 */

const taegeukgiColor = ["white", "black", "red", "blue"];

function isTaegeukgiColor(color) {
  if (taegeukgiColor.includes(color)) {
    return true;
  }
  return false;
}

const color1 = isTaegeukgiColor("red");
const color2 = isTaegeukgiColor("yellow");

console.log(color1);  //true
console.log(color2);  //false

 


② 객체의 괄호 표기법

 

조건문의 return 값이 여러 개 중 하나가 되는 경우에 객체의 프로퍼티에 접근하는 괄호 표기법을 이용하는 방법입니다. 

 

 

[예시 코드]

 

/* 태극기의 어떤 부분에 이용되는 색상인지를 검사 */

const whichPart = (color) => {
  if (color === "white") return "바탕";
  if (color === "black") return "건곤감리";
  if (color === "red" || color === "blue") return "태극 문양";
  return "* 태극기에 사용되는 색상이 아닙니다.";
};

console.log(whichPart("black"));  //건곤감리
console.log(whichPart("red"));    //태극 문양
console.log(whichPart("yellow"));  //* 태극기에 사용되는 색상이 아닙니다.

/* 태극기의 어떤 부분에 이용되는 색상인지를 검사 */

const Taegeukgi = {
  white: "바탕",
  black: "건곤감리",
  red: "태극 문양",
  blue: "태극 문양"
};

const whichPart = (color) => {
  return Taegeukgi[color] || "* 태극기에 사용되는 색상이 아닙니다. ";
};

console.log(whichPart("black")); //건곤감리
console.log(whichPart("red")); //태극 문양
console.log(whichPart("yellow")); //* 태극기에 사용되는 색상이 아닙니다.