Skip to main content

Command Palette

Search for a command to run...

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

Published
2 min read
Control Flow in JavaScript: If, Else, and Switch Explained
S
I write code , that run in the browser and someone else's machine. And sometimes I also write articles

In a typical day to day programming there are a lot of decisions that need to be made inside our code files depending on which we perform different actions.. Typically Conditional operators are used to make such decisions. This decision making and deciding and controlling the flow of the program is called control flow.

We will learn today how we can write control flows for our programs in this article. Let's start

If statements

If statements allow you to perform different actions conditionally based on output of a condition at runtime. Let's take an example

As you can see based on a condition we can conditionally print a congratulate message. This is what a typical control flow looks like. But we can do better.

If-else statement

We can also perform an action if certain condition does not result in a truthy value. Think adding a new entry in a database, what if it fails? user needs to informed of that right?

else if ladder

But what if we are in a situation where there can be many outcomes or possibilities how do handle it then ? when there can be multiple truthy values for different cases?
For that we use following syntax

switch statement

This is used when you want to do simple match based conditioning.

In switch-case you cannot use any expression for that you need to use if-else, in every case it must be a constant. default case is for all the invalid values that does not match with any provided cases. break in each case is must so that the all next case does not execute including default automatically.

Conclusion

This is how we can control the flow of our program and make decision at the runtime dynamically depending of values and conditions. Hopefully now you can use your own control flows.