# Control Flow in JavaScript: If, Else, and Switch Explained



Okay, so programming isn’t just about writing code. It’s about making decisions and about how efficiently your code is written and how well it works.Sometimes we want a program to run a block of code only when a condition is true.

## What control flow means in programming :

Control flow determines how our program moves from one line of code to another. In JavaScript, code normally executes from top to bottom.

For example:

![](https://cdn.hashnode.com/uploads/covers/696b101f5920b7f192ba7dea/fa68d8e4-0ef3-4e1b-84a5-5cd1b58ec9f2.png align="center")

We can see that the code is executed line by line, but in a real-world application we need decisions, so JavaScript provides:

1.  if
    
2.  else
    
3.  else if
    
4.  switch
    

these help to make the decision.

## The `if` statement :

The if statement runs code only when a condition is true.

For example:

![](https://cdn.hashnode.com/uploads/covers/696b101f5920b7f192ba7dea/b71393d1-026e-4378-9c9c-995ee02ecc66.png align="center")

Okay, so the condition inside the if is correct. That is why it prints 'you can boot'. Otherwise it won't print it.

## The `if-else` statement :

the if-else statement is used when we want one block to run if the condition is true and another block to run if the condition is false.

![](https://cdn.hashnode.com/uploads/covers/696b101f5920b7f192ba7dea/6212ae02-a6a0-420f-8c86-a6d39fd3f4e4.png align="center")

## The `else if` ladder :

Okay, sometimes we need to check multiple conditions in this JavaScript to create an else-if ladder.

Example :  

![](https://cdn.hashnode.com/uploads/covers/696b101f5920b7f192ba7dea/c6a4a2da-6e06-4977-8fca-67ceb2886357.png align="center")

## The `switch` statement :

The switch statement is used when we need to compare one value with multiple possible options. It s more cleaner than else if conditions.

![](https://cdn.hashnode.com/uploads/covers/696b101f5920b7f192ba7dea/2e11a590-a830-468d-b9e7-175826eecda3.png align="center")

## When to use switch vs if-else :

**Use Switch :**

*   Multiple fixed values.
    
*   for readibility
    

**Use if-else :**

*   Complex Conditions
    
*   Using logical operators
    
*   Comparing ranges.
    

## Conclusion :

Control flow statements are one of the most important parts of JavaScript because they allow programs to make decisions.
