Skip to main content

Command Palette

Search for a command to run...

Control Flow in JavaScript

If, Else and Switch Explained

Updated
•5 min read•View as Markdown
Control Flow in JavaScript
S
Software Developer | Full Stack Developer |

What Control Flow means in Programming?

Control flow in programming refers to the order in which individual statements, instructions, or function calls are executed or evaluated in a program. By default, code runs sequentially from top to bottom, but control flow mechanisms allow programs to deviate from this linear path based on conditions, loops, or other logic.

Key Aspects of Control Flow:

  • Conditional Statements: Execute different code blocks based on whether a condition is true or false (e.g., if, else, switch).

  • Loops: Repeat a block of code while a condition remains true (e.g., for, while, do-while).

  • Jump Statements: Alter the flow abruptly (e.g., break, continue, return).

  • Function Calls: Transfer control to a function and return to the calling point after execution.

The `if` statement:

The if(...) statement evaluates a condition in parentheses and, if the result is true, executes a block of code.

For example:

let year = prompt('In which year was ECMAScript-2015 specification published?', '');

if (year == 2015) console.log( 'You are right!' );

In the example above, the condition is a simple equality check (year == 2015), but it can be much more complex.

If we want to execute more than one statement, we have to wrap our code block inside curly braces:

if (year == 2015) {
  console.log("That's correct!");
  console.log("You're so smart!");
}

The `if-else statement`:

The if...else statement executes a statement if a specified condition is truthy. If the condition is falsy, another statement in the optional else clause will be executed.

function testNum(a) {
  let result;
  if (a > 0) {
    result = "positive";
  } else {
    result = "NOT positive";
  }
  return result;
}

console.log(testNum(-5));
// Expected output: "NOT positive"

The `else-if` ladder:

Sometimes, we’d like to test several variants of a condition. The else if clause lets us do that.

For example:

let year = prompt('In which year was the ECMAScript-2015 specification published?', '');

if (year < 2015) {
  console.log('Too early...');
} else if (year > 2015) {
  console.log('Too late');
} else {
  console.log('Exactly!');
}

In the code above, JavaScript first checks year < 2015. If that is falsy, it goes to the next condition year > 2015. If that is also falsy, it shows the last alert.

There can be more else if blocks. The final else is optional.

The `switch` statement:

A switch statement can replace multiple if checks.

It gives a more descriptive way to compare a value with multiple variants.

The switch has one or more case blocks and an optional default. The syntax is shown below:

switch(x) {
  case 'value1':  // if (x === 'value1')
    ...
    [break]

  case 'value2':  // if (x === 'value2')
    ...
    [break]

  default:
    ...
    [break]
}
  • The value of x is checked for a strict equality to the value from the first case (that is, value1) then to the second (value2) and so on.

  • If the equality is found, switch starts to execute the code starting from the corresponding case, until the nearest break (or until the end of switch).

  • If no case is matched then the default code is executed (if it exists).

An example of switch (the executed code is highlighted):

let a = 2 + 2;

switch (a) {
  case 3:
    console.log('Too small');
    break;
  case 4:
    console.log('Exactly!');
    break;
  case 5:
    console.log('Too big');
    break;
  default:
    console.log("I don't know such values");
}

Here the switch starts to compare a from the first case variant that is 3. The match fails.

Then 4. That’s a match, so the execution starts from case 4 until the nearest break.

If there is no break then the execution continues with the next case without any checks.

An example without break:

let a = 2 + 2;

switch (a) {
  case 3:
    console.log('Too small');
  case 4:
    console.log('Exactly!');
  case 5:
    console.log('Too big');
  default:
    console.log("I don't know such values");
}

Switch vs If-else:

Use a switch statement when you need to compare a single variable against multiple discrete, fixed values, especially when the values are constants (like integers, characters, or enumerated types). It is more readable and often faster than a long chain of if-else statements because compilers can optimize it using a jump table, enabling constant-time lookups. This makes switch ideal for scenarios like handling menu selections, day-of-week logic, or state machines.

Use if-else statements when:

  • You are testing complex conditions involving ranges, logical expressions, or multiple variables.

  • The conditions are not based on equality to a single variable.

  • You need to evaluate boolean expressions or dynamic values that aren’t known at compile time.

  • You want to avoid fall-through behavior, as switch cases can accidentally fall through if break is omitted.

Conclusion

In this article, we have summed up the main differences and similarities between if-else and switch. These are both very commonly used conditional statements, and to wrap it all up:

  • It is up to the user if they would like to use if else or switch as they both serve the same purpose.

  • Both if-else and switch have their own set of advantages over one another.

  • It is ideal to use if else when checking if a condition is true or false.

  • It is ideal to use a switch instead of using nested if-else statements as it is faster due to the creation of a jump table.

Debunking Fundamentals of JavaScript

Part 8 of 25

This series contains various blogs which explain the basics of javascript from scratch and give an inside working structure of the scripting language.

Up next

Understanding Objects in JavaScript

A deep dive into objects in JavaScript