Conditional Statements in JavaScript
if, else if, else, switch, ternary, truthy and falsy values
Conditional Statements in JavaScript
Conditional statements let your JavaScript program make decisions. Based on whether a condition is true or false, different blocks of code will run. This is the foundation of control flow โ the order in which code executes.
The if Statement
const temperature = 28;
if (temperature > 30) {
console.log('It is hot outside.');
} else if (temperature > 20) {
console.log('It is warm outside.'); // this runs
} else {
console.log('It is cold outside.');
}Truthy and Falsy Values
JavaScript evaluates non-boolean values as either truthy or falsy in conditional contexts. The following six values are falsy: false, 0, '' (empty string), null, undefined, and NaN. Everything else is truthy, including empty arrays and empty objects.
if ('hello') console.log('Truthy'); // runs
if (0) console.log('Truthy'); // does not run
if ([]) console.log('Arrays are truthy'); // runsThe switch Statement
Use switch when you have multiple possible values for the same variable. Each case must end with break to prevent fall-through.
const day = 'Monday';
switch (day) {
case 'Monday':
console.log('Start of the work week.');
break;
case 'Friday':
console.log('Last day of the work week.');
break;
case 'Saturday':
case 'Sunday':
console.log('Weekend!');
break;
default:
console.log('Midweek day.');
}Short-Circuit Evaluation
Logical operators can be used as concise conditionals. The && operator runs the right side only if the left side is truthy. The || operator runs the right side only if the left side is falsy.
const isAdmin = true;
isAdmin && console.log('Welcome, admin!'); // prints
const name = '' || 'Anonymous';
console.log(name); // 'Anonymous'