Ex01. If
const a = 10;
if (a > 15) { //code block
console.log('a is bigger than 15');
} else if ( a === 10) {
console.log('a is 10');
} else {
console.log('This is not a>15 and a===10');
}
Ex02. Switch/case
const device = 'iphone';
switch (device) {
case 'iphone':
console.log('This is iphone');
break; //생략 가능
case 'ipad':
console.log('This is ipad');
break;
default:
console.log('sorry');
}
Ex03. Check if there is the certain value
function isAnimal(text) {
return (
text === 'cat' || text === 'dog' || text === 'turtle' || text === 'bear'
);
}
console.log(isAnimal('dog')); // true
console.log(isAnimal('laptop')); // false
-> Change into the Array
function isAnimal(name) {
const animals = ['cat', 'dog', 'turtle', 'bear'];
return animals.includes(name);
}
console.log(isAnimal('dog')); //true
console.log(isAnimal('laptop')); //false
-> Change into the Arrow Function
const isAnimal = name => ['cat', 'dog', 'turtle', 'bear'].inclues(name);
console.log(isAnimal('dog')); //true
console.log(isAnimal('laptop')); //false
Ex04. Return the different values
(If ver.)
function getSound(animal) {
if (animal === 'dog') return 'siru';
if (animal === 'cat') return 'kitty';
if (animal === 'bird') return 'huhu';
return '...?';
}
console.log(getSound('dog')); //siru
(Switch ver.)
function getSound(animal) {
switch(animal) {
case 'dog':
return 'siru';
case 'cat':
return 'kitty';
case 'bird':
return 'huhu';
default:
return '...?';
}
}
console.log(getSound('dog')); //siru
- Switch는 break 생략 가능
(Object ver.)
function getSound(animal) {
const sounds = {
dog: 'siru',
cat: 'kitty',
bird: 'huhu'
};
return sounds[animal] || '...?';
}
console.log(getSound('dog')); //siru
// 실행 해야하는 코드 구문이 다를 때 -> add functions
function makeSound(animal) {
const tasks = {
dog() {
console.log('siru');
},
cat() {
console.log('kitty');
},
bird() {
console.log('huhu');
}
}
if (!tasks[animal]) {
console.log('...?');
return;
}
tasks[animal]();
}
makeSound('dog');
makeSound('bird');