Skip to content

Instantly share code, notes, and snippets.

@Lakshay-Batra
Last active June 30, 2020 13:28
Show Gist options
  • Select an option

  • Save Lakshay-Batra/006ea7fb95afa1ffef2c758a4cf681ec to your computer and use it in GitHub Desktop.

Select an option

Save Lakshay-Batra/006ea7fb95afa1ffef2c758a4cf681ec to your computer and use it in GitHub Desktop.

Conditionals

While programming there comes a point where you need to make decisions and carry out actions accordingly depending on different inputs. This can be achieved by if...else statements, switch statement and ternary operator.

1. Basic if else

Used when you want to check just a single condition and carry out actions accordingly

var rainy = true;
if(rainy) {
  console.log("It will rain today");
} else {
    console.log("It will not rain today");
  }
//expected output: "It will rain today"

else if

Used when you want to check more than one conditions and carry out actions accordingly

var rainy = 'yes';
if(rainy === 'yes') {
  console.log("It will rain today");
 } else if(rainy === 'no') {
    console.log("It will not rain today");
   } else {
      console.log("Uncertain about the rain");
     }
//expected output: "It will rain today"

Note: you can use multiple else if statements

2. Switch statement

It is another way to make decisions according to the conditions and carry out actions accordingly. Previous example using switch statement is framed below.

var rainy = 'yes';
switch (rainy) {
    case 'yes':
      console.log("It will rain today");
      break;
    case 'no':
      console.log("It will not rain today");
      break;
    default:
      console.log("Uncertain about the rain");
}
//expected output: "It will rain today"

Note: It is personally suggested to use switch instead of else if only when you have to check 5 or more conditions

3. Ternary operator

This operator is frequently used as a shortcut for the if else statement.

var rainy = true;
(rainy) ? console.log("It will rain today") : console.log("It will not rain today");
//expected output: "It will rain today"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment