본문 바로가기
Front-End/JavaScript

Learn JavaScript_Conditionals

by SoyeonCha 2022. 7. 14.

∘ Math.round() : 반올림

∘ Math.ceil() : 올림

∘ Math.floor() : 내림

Magic Eight Ball

let userName = 'J';
userName ? console.log(`Hello, ${userName}`) : console.log('Hello!');
let userQuestion = 'Will I adopt a new puppy soon?';
console.log(`${userName} has asked - ${userQuestion}`);
let randomNumber = Math.floor(Math.random() * 8);
let eightBall = '';
switch (eightBall){
  case 0 :
    eightBall = 'It is certain';
    break;
  case 1 :
    eightBall = 'It is decidedly so';
    break;
  case 2 :
    eightBall = 'Reply hazy try again';
    break;
  case 3 :
    eightBall = 'Cannot predict now';
    break;
  case 4 :
    eightBall = 'Do not count on it';
    break;
  case 5 :
    eightBall = 'My sources say no';
    break;
  case 6 :
    eightBall = 'Outlook not so good';
    break;
  case 7 :
    eightBall = 'Signs point to yes';
    break;
}
console.log(`The Magic 8 Ball says, ${eightBall}`);

Race Day

let raceNumber = Math.floor(Math.random() * 1000);
let early = true;
let age = 23;

if (early && age>18) {
  raceNumber += 1000;
  console.log(`Race will begin at 9:30, your race number is: ${raceNumber}`);
}
else if (!early && age>18){
  console.log(`Race will begin at 11:00, your race number is: ${raceNumber}`);
}
else if (age<18){
  console.log(`Race will begin at 12:30, your race number is: ${raceNumber}`);
}
else{
  console.log('Please approach the registration desk, thanks!');
}

 

 ===는 value 비교 위해 쓰임

 

if (walkSignal === 'Walk') {
    console.log('You may walk!'); 
} else {   
    console.log('Do not walk!');
}

위 코드를 ternary operator를 이용하는 걸로 바꾸면

앞이 walkSignal ? console.log ...이 아니라

walkSignal === 'Walk' ? console.log('You may walk!') : console.log('Do not walk!); 임

 

conditional statements의 general purpose는 코드를 true 또는 false로 판단하는 것