특정 값이 여러값 중 하나인지 확인해야 할 때
includes
비교해야 할 값이 많아질 수록 코드는 길어지게 된다.
function isAnimal(text) {
return (
text === '고양이' || text === '개' || text === '거북이' || text === '너구리'
);
}
console.log(isAnimal('개')); // true
console.log(isAnimal('노트북')); // false
이러한 코드를 간단하게 해결할 수 있는 방법은, 배열에 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
값에 따라 다른 결과물을 반환해야 할 때
switch
예) 동물 이름을 받아오면 동물의 소리를 반환하는 함수
function getSound(animal) {
if (animal === '개') return '멍멍!';
if (animal === '고양이') return '야옹~';
if (animal === '참새') return '짹짹';
if (animal === '비둘기') return '구구 구 구';
return '...?';
}
console.log(getSound('개')); // 멍멍!
console.log(getSound('비둘기')); // 구구 구 구
여기서 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('비둘기')); // 구구 구 구
이 코드를 더욱 깔끔하게 작성하면 다음과 같이 작성할 수 있다.
function getSound(animal) { // getSound - 소리를 받아와서 직접 출력
const sounds = {
개: '멍멍!',
고양이: '야옹~',
참새: '짹짹',
비둘기: '구구 구 구'
};
return sounds[animal] || '...?';
}
console.log(getSound('개')); // 멍멍!
console.log(getSound('비둘기')); // 구구 구 구
객체를 생성한 뒤 sounds[animal]
파라미터로 받아온 animal
을 객체 내부에서 비교한 후 존재하면 sounds[animal]
을 출력하고 존재하지 않으면 '...?'
을 출력하는 함수이다.
이렇게 특정값에 따라 반환해야 하는 값이 다른 조건이 여러가지 있을 때는 객체를 활용하면 좋다.
값에 따라 실행해야 하는 코드 구문이 다를 때
그럴 때는 객체에 함수를 넣으면 된다.
function makeSound(animal) {
const tasks = {
개() {
console.log('멍멍');
},
고양이() {
console.log('고양이');
},
비둘기() {
console.log('구구 구 구');
}
};
if (!tasks[animal]) {
console.log('...?');
return;
}
tasks[animal]();
}
makeSound('개');
makeSound('비둘기');