Programación Para Tontos

JavaScript

Tutorial: conditionals in JavaScript - a decision-making traffic light

Learn if, else, and else if by building a traffic light that decides which message to show.

Your code, just like you, needs to make decisions all day long: "if the user is logged in, show this; if not, show that instead". That's called a conditional, and today you'll build a traffic light with them.

Step 1: the simplest if

const color = 'red';

if (color === 'red') {
  console.log('Stop');
}

if (condition) runs the block only if the condition is true. If color weren't 'red', nothing would happen. Thrilling, I know.

Step 2: add an else

if (color === 'red') {
  console.log('Stop');
} else {
  console.log('You can go');
}

else is plan B: it runs when the if is false. Now your code always says something, instead of going silent like when someone asks if you saw their message.

Step 3: chain multiple options with else if

function trafficLight(color) {
  if (color === 'red') {
    return 'Stop';
  } else if (color === 'yellow') {
    return 'Get ready';
  } else if (color === 'green') {
    return 'Go';
  } else {
    return 'Unknown color';
  }
}

console.log(trafficLight('yellow')); // 'Get ready'

else if lets you check several conditions in order, top to bottom, until one is true. That final else is your safety net for when nothing else applies (like when someone passes a color that doesn't exist, because there's always someone).

Bonus challenge

Update trafficLight so that if you pass a color in uppercase ('RED'), it still works correctly. Hint: look up the .toLowerCase() method.

What did you just learn?

  • How to use if, else, and else if to make decisions.
  • That conditions are evaluated in order, top to bottom.
  • That a good final else keeps your code from going silent.