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.
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"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
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
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"