Script Valley
JavaScript Tutorial for Beginners to Advanced
Control Flow and FunctionsLesson 3.1

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'); // runs

The 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'

Up next

JavaScript Loops

Sign in to track progress

Conditional Statements in JavaScript โ€” Control Flow and Functions โ€” JavaScript Tutorial for Beginners to Advanced โ€” Script Valley โ€” Script Valley