JS-044
Visual JavaScript guide to else: Learn to define an alternative path using else
Beginner4 min~4 min read#else#if-else#condition

else

What to do otherwise

Goal

Learn to define an alternative path using else.

Explanation

  • else works together with if.
  • If the if condition returns false, the else block runs.
  • This lets you describe two different paths.
  • One path is for true, and the other is for false.
  • This is the most common form of branching in programming.

Analogy

If it is sunny, you go for a walk. Otherwise, you stay home. else describes the “otherwise” option.

Code

if (isSunny) {
  console.log("Go outside");
} else {
  console.log("Stay home");
}

Result: Stay home

Common mistake

Beginners sometimes think else checks a new condition. In fact, else simply runs when the preceding condition did not pass.

Remember

  • else runs when if returns false.
  • if and else describe two possible paths.
  • else cannot exist without if.

Quick Quiz

When does else run?

Resources