Skip to main content

Command Palette

Search for a command to run...

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

Updated
7 min read

What will we Learn?

In this blog we are going to study about the topics listed given below:

  • What are conditionals? Why do we need them?

  • If, else if, else ladder

  • Switch-case

  • When to use what?

Fun blog fun topics fun language, sit back relaxed and have a tea :)

What are Conditionals? Why Conditionals?

What are conditionals?

  • Conditionals are statements that allow us to perform specific function if specific conditions are met.

  • One practical case of this would be your college they check whether your ID card to verify whether you are a student of there college or not if yes, then they'll allow you to enter if no they'll not. That's Conditionals!

Why Conditionals?

  • The reason is pretty simple we sometimes want to perform some functions only if a specific condition is met.

  • Back to our college example we must verify that if we won't verify then everyone can enter the college. That would create a total mess wouldn't that?

If, else if, else Ladder

This is the part where you'll learn conditionals so the first and foremost is the if, else if, else ladder.

Let's see what each one of them do

If

This is always the first condition in this ladder and this is always and always checked.

// Syntax

if (condition) {
   // functions to perform
}

Let's understand the syntax and logic flow by looking at the code:

  • In this code first we are declaring that this is an if statement using the keyword.

  • In the parentheses we write the condition to be checked.

  • In those curly braces we write that what functions are to be applied.

  • We can write multiple if statements.

// Use Case

let age = 15

if (age < 13) {
    console.log("You are a child")
}
if (age < 20 && age > 13) {
    console.log("You are a teenager")
}
if (age > 20) {
    console.log("You are an adult")
}

// output would be "You are a teenager" because the value of age doesn't made any other criteria

else If

This is condition that always lies between if and else statements. Checked only if the if statement doesn't match.

Syntax:

// Syntax

if (condition) {
   // functions to perform
} else if (condition) {
   // functions to perform
}
  • In this code first we are declaring that this is an if statement using the keyword.

  • After the if we are declaring an else if statement which is just as same as if.

  • The only different is that all if statements are checked but all else if statements aren't checked once a else if statements meets the criteria the further checking stops.

Now. remember the age category code that we have just written in the upper section do you think does it makes sense to check whether a particular age lies between adult or teenager category even thought they are already in the child category?

No, right so let's remake our code using else if statements

// Use Case

let age = 15

if (age < 13) {
    console.log("You are a child")
} else if (age < 20) {
// Removed other validation because it's already getting checked by the if statement
    console.log("You are a teenager")
} else if (age > 20) {
    console.log("You are an adult")
}

// output would be "You are a teenager" and as soon as we get that output further checking of conditions would be stopped.

else

This is the default condition that means it will run if none of the other conditions were not met

Syntax:

// Syntax

if (condition) {
   // functions to perform
} else if (condition) {
   // functions to perform
} else {
   // functions to perform
}
  • In this code first we are declaring that this is an if statement using the keyword.

  • After the if we are declaring an else if statement.

  • and finally, else where no condition is required because it's the default case.

Do you think in our age category code if a particular age is neither a child nor a teenager than that would be adult?

Yes, that would be so let's make our code that way

// Use Case

let age = 20

if (age < 13) {
    console.log("You are a child")
} else if (age < 20 && age > 13) {
    console.log("You are a teenager")
} else {
    console.log("You are an adult")
}

// output would be "You are am adult" because the code won't match any of the upper tow criteria so, default case will run.

Some important things to remember

  • All if statements are checked doesn't matter if one matched or not

  • If all if statements don't match then else if will start running one by one as soon as one matches the whole checking stops.

  • else will run only if both if and else if didn't matched.

  • if statement must lie at the 1st position in a if, else if, else ladder.

  • There can be single, multiple or no else if statements.

  • There can be single or no else statements multiples aren't allowed here like think about it can there be 2 defaults? No, definitely not.

Switch-Case

Another conditional, used of just 2 things 1 switch and multiple cases sometimes third guy default appears too.

// Syntax

switch (expression) {
  case value1:
    // function to be performed
    break;
  case value2:
    // function to be performed
    break;
  default:
    // function to be performed
}
  • First, we declare that this is a switch statement using the switch keyword.

  • Then we give the expression in the parentheses usually a variable.

  • Then we start curly braces and inside them we write cases.

  • Cases are declared with case keyword with a colon at the end of them.

  • They just have a value to check whether there value matches the value passed in the switch,

  • If yes, then they perform the functions they were here to perform.

  • else they go for the next case.

  • If fails all the cases goes to default and default runs.

  • The break in each case stops the code for checking further conditions if met one case.

// implementation

const favFruit = "mango"

switch (favFruit) {
  case "apple":
    console.log("One Apple a day keeps the doctor away")
    break;
  case "banana":
    console.log("It's time to bulk up")
    break;
  default:
    console.log(`Don't know about ${favFruit} that much`)
}

// output would be Don't know about mango that much because all the other cases will not match

When to Use What?

When to use if, else if, else ladder?

When you have to check for a condition or you have to perform some operations on the conditions or compare two values go this way.

When to use switch-case?

When you just have to check a single value the switch-case would be more handy.

Conclusion

Today we learnt about 2 conditionals and their use cases.

When to use what is a topic that you'll learn on your own as you'll build something.

Go ahead take some challenges from ChatGPT or Claude.

Hope it helped :)

JavaScript: Everything you should know

Part 4 of 26

This is your ultimate guide towards JavaScirpt, this series of articles include - JavaScript Operators: The Basics You Need to Know - Understanding Variables and Data Types in JavaScript - Template Literals in JavaScript - Control Flow in JavaScript: If, Else, and Switch Explained - Array Methods You Must Know - JavaScript Arrays 101 - Function Declaration vs Function Expression: What’s the Difference? - Arrow Functions in JavaScript: A Simpler Way to Write Functions - Understanding Objects in JavaScript - Spread vs Rest Operators in JavaScript - Destructuring in JavaScript - Map and Set in JavaScript - Understanding Object-Oriented Programming in JavaScript - Understanding the this Keyword in JavaScript - The new Keyword in JavaScript - The Magic of this, call(), apply(), and bind() in JavaScript - Array Flatten in JavaScript - String Polyfills and Common Interview Methods in JavaScript - Synchronous vs Asynchronous JavaScript - Callbacks in JavaScript: Why They Exist - JavaScript Promises Explained for Beginners - Promise Methods Explained: CID Analogy - Async/Await in JavaScript: Writing Cleaner Asynchronous Code - Error Handling in JavaScript: Try, Catch, Finally - JavaScript Modules: Import and Export Explained - The Part of Events You Never See The following 26 articles and topics are covered

Up next

JavaScript Arrays 101

What will we Study? In this blog, we are going to learn about the following topics: What are Arrays? Why do we need them? Array Basics Looping through an Array The blog contains cool code example

More from this blog

L

Learning Tech

61 posts

A Blog with dozens of articles on different langauges as well as frameworks, This isn't just for you to learn, i crafted it thinking that this could be my future reference as well

It covers Networking, Web Development, Mobile Developement and very soon GenAI too!