Welcome to Day 4 of our 30-day JavaScript and Node.js learning series! In the last article, we introduced you to the basics of JavaScript syntax. Today, we’ll dive deeper into one of the most crucial topic—control flow in JavaScript.
Introduction to Control Flow
Control flow refers to the order in which statements are executed in a JavaScript program. By default, JavaScript code is executed from top to bottom line by line. This can be changed using control flow.
It allows you to make decisions and execute code conditionally or repeatedly based on certain conditions.
By understanding control flow, you can create more dynamic and flexible applications.
Types of Control flow statements
- Conditional Statements – These statements are used for decision making. This basically check whether a certain condition is satisfied or not, then decides which code need to be executed.
- If Statements
- Switch
- Ternary
- Iterative Statements – This statement executes the code repeatedly until a certain condition is met. Loops allows us to perform repetitive tasks with less code.
- For loop
- do/while loop
- for…in
- for…of
General Control Flow Graphs
Conditional Statements

If Statement

If-else Statement

If-else-if Statement

Switch case Statement
Iterative Statements

For loop

While loop

Do-while loop
Get all the control flow graph downloaded below.
If Statements
If statements are the most basic form of control flow in JavaScript. They allow you to execute a block of code only if a certain condition is true. The syntax for an if statement is as follows:
if (condition) {
// Code to be executed if the condition is true
}
Here’s an example of using an if statement:
let age = 18;
if (age >= 18) {
console.log("You are eligible to vote.");
}
In this example, the code inside the if
block will only be executed if the value of age
is greater than or equal to 18.
Else and Else If Statements
You can use else
and else if
clauses to provide alternative actions based on different conditions. The else
clause is executed if the if
condition is false. The else if
clause allows you to check additional conditions before executing the else
clause.
Here’s an example of using else
and else if
statements:
let grade = 85;
if (grade >= 90) {
console.log("Excellent!");
} else if (grade >= 80) {
console.log("Good job!");
} else {
console.log("Needs improvement.");
}
In this example, the code will output “Excellent!” if grade
is greater than or equal to 90, “Good job!” if grade
is greater than or equal to 80, and “Needs improvement.” otherwise.
Switch Statements
Switch statements provide a more concise way to compare a value against multiple cases. The syntax for a switch statement is as follows:
switch (expression) {
case value1:
// Code to be executed if expression equals value1
break;
case value2:
// Code to be executed if expression equals value2
break;
// ...
default:
// Code to be executed if no case matches
}
Here’s an example of using a switch statement:
let dayOfWeek = "Wednesday";
switch (dayOfWeek) {
case "Monday":
console.log("It's a workday.");
break;
case "Tuesday":
case "Wednesday":
case "Thursday":
case "Friday":
console.log("It's a weekday.");
break;
case "Saturday":
case "Sunday":
console.log("It's the weekend!");
break;
default:
console.log("Invalid day.");
}
In this example, the switch statement compares the value of dayOfWeek
against different cases and executes the corresponding code. The break
statement is used to exit the switch statement once a matching case is found.
For Loops
For loops are used to execute a block of code a specified number of times. They are often used to iterate over arrays or perform repetitive tasks. The syntax for a for loop is as follows:
for (initialization; condition; increment/decrement) {
// Code to be executed
}
Here’s an example of using a for loop to iterate over an array:
let numbers = [1, 2, 3, 4, 5];
for (let i = 0; i < numbers.length; i++) {
console.log(numbers[i]);
}
In this example, the for loop iterates over each element in the numbers
array and logs it to the console.
Other than the general for loop, JavaScript has other two for loop; for…in and for…of.
- for…in – iterates over all enumerable property keys of an object.
- for…of – iterates over the values of an iteratable object.
While and Do…While Loops
These are used for indefinite iteration. While loops continue to execute as long as a specified condition is true. Do…while loops execute at least once, even if the condition is false initially.
Here’s an example of using a while loop:
let count = 0;
while (count < 5) {
console.log("Count:", count);
count++;
}
In this example, the while loop continues to execute as long as count
is less than 5.
Here’s an example of using a do…while loop:
let input;
do {
input = prompt("Enter a number:");
} while (isNaN(input));
console.log("You entered:", input);
In this example, the do…while loop prompts the user for a number until the user enters a valid number.
Break and Continue Statements
The break
statement is used to exit a loop prematurely. The continue
statement is used to skip the current iteration of a loop and proceed to the next iteration.
Here’s an example of using break
to exit a loop:
for (let i = 1; i <= 10; i++) {
if (i === 5) {
break;
}
console.log(i);
}
In this example, the loop will break when i
reaches 5.
Here’s an example of using continue
to skip an iteration:
for (let i = 1; i <= 5; i++) {
if (i === 3) {
continue;
}
console.log(i);
}
In this example, the loop will skip the iteration where i
is 3.
Additional Tips
- Nested conditions and loops: You can nest if statements, switch statements, and loops within each other to create more complex control flow structures.
- Logical operators and comparison operators: These operators allow you to combine conditions and compare values.
- Ternary operator: The ternary operator provides a concise way to write conditional expressions.
- Code blocks and indentation: Use code blocks and proper indentation to improve readability and maintainability of your code.
Summary
Control flow is a fundamental concept in JavaScript that determines the order in which statements are executed. It allows you to make decisions and execute code conditionally or repeatedly based on certain conditions.
Key control flow structures in JavaScript include:
- If statements: Used to execute code conditionally based on a condition.
- Else and Else If statements: Provide alternative actions based on different conditions.
- Switch statements: Compare a value against multiple cases and execute the corresponding code.
- For loops: Used to execute a block of code a specified number of times.
- While and Do…While loops: Used for indefinite iteration.
- Break and Continue statements: Used to control the execution of loops.
By understanding and effectively using control flow structures, you can create more dynamic, efficient, and flexible JavaScript applications.
Conclusion
Understanding control flow is essential for writing effective and dynamic JavaScript code. By using if statements, switch statements, loops, and break/continue statements, you can make decisions, execute code conditionally, and iterate over data. In the next article, we’ll explore JavaScript Functions, taking your understanding to the next level!
Previous Lesson
Next Lesson
Day 5: Functions in JavaScript
Share the lessons with your friends
Very well written information. It will be beneficial to anybody who utilizes it, including myself. Keep up the good work – can’r wait to read more posts.
Everything is very open and very clear explanation of issues. was truly information. Your website is very useful. Thanks for sharing.
I’ve been browsing on-line more than three hours these days, yet I by no means found any interesting article like yours. It is lovely worth sufficient for me. Personally, if all website owners and bloggers made good content material as you probably did, the net will likely be a lot more useful than ever before.
Exactly what I was searching for, thankyou for posting.
My developer is trying to persuade me to move to .net from PHP. I have always disliked the idea because of the expenses. But he’s tryiong none the less. I’ve been using WordPress on various websites for about a year and am worried about switching to another platform. I have heard great things about blogengine.net. Is there a way I can transfer all my wordpress content into it? Any help would be greatly appreciated!
Can I just say what a relief to find somebody who actually knows what theyre talking about on the internet. You definitely know how to convey a difficulty to mild and make it important. More folks need to learn this and understand this facet of the story. I cant imagine youre no more common because you positively have the gift.
I really appreciate this post. I¦ve been looking all over for this! Thank goodness I found it on Bing. You’ve made my day! Thanks again
I got what you intend, thankyou for putting up.Woh I am lucky to find this website through google. “Success is dependent on effort.” by Sophocles.
Wow, awesome blog layout! How long have you been blogging for? you make blogging look easy. The overall look of your website is great, as well as the content!
Definitely believe that which you said. Your favourite reason seemed to be at the net the simplest thing to take into accout of. I say to you, I definitely get annoyed while people think about issues that they plainly do not recognize about. You controlled to hit the nail upon the top and outlined out the entire thing without having side-effects , other people can take a signal. Will probably be again to get more. Thank you
Hmm it appears like your website ate my first comment (it was extremely long) so I guess I’ll just sum it up what I submitted and say, I’m thoroughly enjoying your blog. I as well am an aspiring blog writer but I’m still new to everything. Do you have any helpful hints for beginner blog writers? I’d certainly appreciate it.
I haven’t checked in here for some time since I thought it was getting boring, but the last few posts are great quality so I guess I’ll add you back to my daily bloglist. You deserve it my friend 🙂
I wanted to thank you for this great read!! I definitely enjoying every little bit of it I have you bookmarked to check out new stuff you post…
It’s actually a cool and helpful piece of info. I am glad that you shared this helpful information with us. Please keep us up to date like this. Thanks for sharing.
The next time I read a blog, I hope that it doesnt disappoint me as much as this one. I mean, I know it was my choice to read, but I actually thought youd have something interesting to say. All I hear is a bunch of whining about something that you could fix if you werent too busy looking for attention.
Some really excellent posts on this website , thanks for contribution.
I simply couldn’t depart your site prior to suggesting that I actually enjoyed the usual information a person supply in your visitors? Is going to be back continuously in order to investigate cross-check new posts.
Thanks for helping out, wonderful info. “If you would convince a man that he does wrong, do right. Men will believe what they see.” by Henry David Thoreau.
naturally like your website but you have to check the spelling on quite a few of your posts. Several of them are rife with spelling problems and I find it very bothersome to tell the truth nevertheless I’ll definitely come back again.
I am impressed with this site, very I am a big fan .
An interesting discussion is worth comment. I think that you should write more on this topic, it might not be a taboo subject but generally people are not enough to speak on such topics. To the next. Cheers
I?¦m now not positive where you’re getting your info, however good topic. I needs to spend a while studying much more or working out more. Thank you for magnificent info I used to be on the lookout for this information for my mission.
Thank you for some other informative blog. The place else may just I get that type of info written in such an ideal manner? I’ve a project that I’m simply now running on, and I’ve been on the glance out for such info.
you are truly a excellent webmaster. The web site loading velocity is incredible. It seems that you are doing any unique trick. Also, The contents are masterwork. you have performed a excellent job on this subject!
Thank you for sharing with us, I think this website genuinely stands out : D.
Good info. Lucky me I reach on your website by accident, I bookmarked it.
Normally I don’t read post on blogs, but I wish to say that this write-up very forced me to try and do it! Your writing style has been amazed me. Thanks, quite nice article.
Its great as your other posts : D, thanks for putting up.
Outstanding post however I was wondering if you could write a litte more on this topic? I’d be very grateful if you could elaborate a little bit more. Many thanks!
You are a very intelligent individual!
It is perfect time to make some plans for the future and it is time to be happy. I’ve read this post and if I could I want to suggest you few interesting things or suggestions. Perhaps you could write next articles referring to this article. I wish to read more things about it!
Hi, just required you to know I he added your site to my Google bookmarks due to your layout. But seriously, I believe your internet site has 1 in the freshest theme I??ve came across. It extremely helps make reading your blog significantly easier.
I’m still learning from you, while I’m improving myself. I definitely liked reading everything that is written on your website.Keep the information coming. I enjoyed it!
Throughout the awesome design of things you actually get a B- just for effort. Where exactly you lost me personally ended up being in your details. As it is said, the devil is in the details… And it couldn’t be much more true at this point. Having said that, permit me inform you exactly what did give good results. Your article (parts of it) can be really powerful which is possibly why I am taking an effort in order to comment. I do not really make it a regular habit of doing that. Secondly, whilst I can easily notice the jumps in reason you come up with, I am definitely not sure of just how you appear to unite your details which inturn make your conclusion. For now I will, no doubt yield to your issue however wish in the near future you actually link your facts better.
What i do not realize is actually how you are not actually much more smartly-appreciated than you may be right now. You’re very intelligent. You understand thus considerably with regards to this subject, made me for my part imagine it from a lot of various angles. Its like men and women aren’t fascinated unless it is something to accomplish with Lady gaga! Your individual stuffs excellent. All the time care for it up!
I really like your writing style, wonderful information, regards for putting up :D. “Much unhappiness has come into the world because of bewilderment and things left unsaid.” by Feodor Mikhailovich Dostoyevsky.
I consider something truly interesting about your blog so I saved to favorites.
I just like the helpful information you supply to your articles. I’ll bookmark your blog and check once more here regularly. I am quite sure I’ll be informed many new stuff proper right here! Good luck for the following!
Hi my friend! I want to say that this post is awesome, nice written and include almost all significant infos. I would like to see more posts like this.
Oh my goodness! an incredible article dude. Thanks Nonetheless I’m experiencing situation with ur rss . Don’t know why Unable to subscribe to it. Is there anybody getting identical rss drawback? Anybody who is aware of kindly respond. Thnkx
I have recently started a web site, the information you offer on this website has helped me greatly. Thank you for all of your time & work.
I’ll right away clutch your rss as I can’t in finding your email subscription link or newsletter service. Do you have any? Kindly permit me recognize in order that I may just subscribe. Thanks.
I take pleasure in, cause I discovered exactly what I was taking a look for. You have ended my four day long hunt! God Bless you man. Have a great day. Bye