[JavaScript] Conditional statement

Cadet_42ยท2021๋…„ 8์›” 9์ผ
0

JavaScript

๋ชฉ๋ก ๋ณด๊ธฐ
6/8
post-thumbnail

Conditional statement

๐Ÿ”ฎif -else statement

The else statement is executed when the ifstatement condition is false.

if (condition) {
  // statements
} else {
  // statements
}

๐Ÿ”ฎ The else if statement

To be able to chain multiple conditions, we useelse ifstatements. The else if statement is executed when the previous if or else if statement condition is false.

if (condition1) {
  // statements
} else if (condition2) {
  // statements
} else if (condition3) {
  // statements
} else {
  // if all above turn to be false,
  // this block of code will be executed
}

โœ๏ธ One very important syntax rule to follow when writing your if, else if and else statements is:

  • if and else if statements always require a condition in order to work,
  • else statements do not need a condition, as it means to run the block of code in every other possible case.

๐Ÿ”ฎ Switch

The value of the variable pet is actually โ€œdogโ€, so it will find if โ€œdogโ€ is one of the cases in the switch block and execute the statement inside.

JSResult Skip Results Iframe
EDIT ON
let pet = "dog";

switch (pet) {
  case "cat":
    console.log("I will be break a lot of things but hey, I'm adorable ... ")
    break;
  case "dog":
    console.log("I will be very annoying but I'm your best friend ... ")
    break;
  case "hamster":
    console.log("I will be impossible to find but I'm reeeeaaaally cute ... ")
    break;
  default:
    console.log("I'm a special pet!")
    break;
}

๐Ÿ”ฎ break

  • The break statement finshes a block execution such as conditionl blocks or loop blocks, and continues with the execution of the program.
  • In programming, you will use break very rarelym because you should be able to control the flow of your program instead of break in it.

Switch break cheatsheet

profile
์•ˆ๋…•ํ•˜์„ธ์š”! ๊ฐœ๋ฐœ๊ณต๋ถ€๋ฅผ ํ•˜๊ณ  ์žˆ์Šต๋‹ˆ๋‹ค. ๊ฐ์‚ฌํžˆ ๋ฐฐ์šฐ๊ฒ ์Šต๋‹ˆ๋‹ค. ;)

0๊ฐœ์˜ ๋Œ“๊ธ€