자바스크립트-조건문 더 스마트하게 쓰기

BackEnd_Ash.log·2020년 3월 29일
1

자바스크립트

목록 보기
8/29

참고자료 https://learnjs.vlpt.us/useful/05-smarter-conditions.html

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

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

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

오호 이렇게도 사용할수 있네요..
저는 if 문 하나 에 또는 으로 여러개 걸어서 해당하면 return 으로 text 돌려주면 되겠네 ? 라는 생각을 했는데
.. ㅠㅠㅠㅠ

뭐.. 어쨌든 이거나 저거나 비교할 값이 많아 질수록 코드가 길어지게 됩니다.
흠.. 반복문 돌리면 되지않을까 ? 라는 생각도 드는데..

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

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

자스에 includes 함수를 사용하면 훨씬 깔끔하게 되네용 .
그리고 이것을 다시 화살표 함수로 바꾸게 된다면 ??

const isAnimal = name => ['고양이' , '개' , '거북이' , '너구리'].includes(name);

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

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

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

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

네.. 다 이해가시죠 ??
switch case 문으로도 구현 할수 있다고 하는데 예상이 되네요
다시 보겠습니다.

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

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

네~ 더 길어졌어요

자스의 매력에 지금 빠진 나는 무한신뢰를 하고있기에 , 깔끔하게 코드를 바꿀수있을꺼라 믿고 밑에 더 읽어보겠습니다.

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

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

함수안에 객체가 있네요 .
그리고 getSound 함수를 호출해서 '개' 를 인자로 넣게 되면 animal 로 들어가게 되겠고
return 할때 sounds['개'] 가 되어서 '개' 라는 키값을 가진 것을 찾아서 value 멍멍을 return 해 줍니다.

그리고 값에 따라 실행해야 하는 코드 구문이 다를 때는 어떻게 해야할까요 ?? 라고 적혀있는데 .
값에 따라 다른 함수를 호출하면 되지않나?? 라는 저의 .. 무식한 생각을 해봅니다.

하지만 자스에서는 객체에 함수를 넣는다고 하네요

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

getSound('개');
getSound('비둘기');
  const tasks = {
    () {
      console.log('멍멍');
    },
    고양이() {
      console.log('고양이');
    },
    비둘기() {
      console.log('구구 구 구');
    }
  };

이게 실행하기 전에
우선적으로
tasks[animal](); 이것이 먼저 실행이 되어서 ,
값에 맞게 console.log 를 실행할것 같습니다.

profile
꾸준함이란 ... ?

2개의 댓글

comment-user-thumbnail
2020년 3월 30일

makeSound 쪽에 getSound라고 오타 있는거 같아요!
좋은 내용 감사합니다!

1개의 답글