Getting started with JS loops

Kelsy Mnk - Dec 26 '22 - - Dev Community

Loops are an essential tool in JavaScript that can greatly improve the efficiency and simplicity of your code, and are a key construct to master to become proficient in the language.

In this article, you are going to learn the three most important types of loops. You'll learn how they work and how you can apply them in your code.

Let's dive right into it, shall we? :)


Before we get started, I'd like to quickly talk about Control Flow Statement which is an important feature in the programming world. It will also help you understand loops more effectively.

What's a control flow statement ?🤔
As the name suggests, it allows you to control the flow of execution of your code. This will allow you to perform repetitive tasks such as loops or write complex programs that can adapt to different situations.


'For' loops 🔁

The for loop is a control flow statement in JavaScript that allows you to repeat a block of code a certain number of times. It is often used to iterate over the elements of an array or to perform a certain task repeatedly and is best suited for situations where you know exactly how many times you want to execute a block of code.

Here is the basic syntax for a for loop in JS

for (initialization; condition; increment) {
  // code to be executed
}
Enter fullscreen mode Exit fullscreen mode

For example:

var timer = [4,3,2,1]

for(var i = 0; i < timer.length; i++) {
    console.log(`You have ${timer[i]} seconds left!`);
}

// Output: You have 4 seconds left!
//         You have 3 seconds left!
//         You have 2 seconds left!
//         You have 1 seconds left!
Enter fullscreen mode Exit fullscreen mode

As you can see in the example shown above, we are displaying how many seconds we have left.

The code is simply saying:
'As long as the i variable is less than the number of elements that are inside of the timer variable, keep displaying what's inside the timer'.
In short, the i var represents the number of times the code has to iterate through the timer array.

Okay but..what if I don't know how many times I want to execute a block of code? Well, this is where the while loop comes in clutch! :)


'While' loops 🔁

A while loop is also a control flow statement that will let you repeat a block of code but an unknown number of times.
It has an indeterminate number of iterations and is best suited for situations where you don't know how many times you want to execute a block of code.

Here is the syntax for a while loop 👇

while (condition) {
  // code to be executed
}
Enter fullscreen mode Exit fullscreen mode

The condition is a boolean expression that is evaluated before each iteration of the loop.
If the condition is true, the loop will continue to execute.
Else, if the condition is false, the loop will terminate.

Let me give you an example :)

var input = "";

while (input !== "stop") {
  input = prompt("Enter a word (type 'stop' to exit):");
  console.log(input);
}
Enter fullscreen mode Exit fullscreen mode

In this example, the while loop will continue to ask the user for input until they enter the word "stop". The input variable is initialized to an empty string before the loop starts, and the loop condition is checked before each iteration of the loop.
If the value of input is equal to "stop", the loop will terminate, else the loop will continue to execute.

Great! We've learned that the while loop checks for the condition first before running. But one more thing..What if I'd like my code to run at least once, before checking for the condition? That's where the do..while loop comes in.

But, why would I need to run the code before checking the condition; you may ask. Well, let me give you a real-world scenario.


Real-world scenario

Suppose, you want to get a free trial of a music app first, then pay a month later.
By using the do..while loop, it would simply go like that: "Run the music app first, then check for the payment."
But if we use the while loop, the code will need to first check for the condition (in this case for the payment) meaning you can't get a free trial since you need to pay first.

You got it? :) If not, feel free to check this simplified youtube video 👈
Alright, now let's transform this example into code for a better understanding.

'Do..While' loops 🔁

The do...while loop is similar to a while loop, except that the loop body is always executed at least once, even if the condition is false. It is useful for situations where you want to ensure that the loop body is executed at least once before the condition is checked.

Example 💻

var musicAppPayment;

do {
  console.log("Here is your free trial<3");
} while (musicAppPayment <= 0);

//Ouput: Here is your free trial<3
Enter fullscreen mode Exit fullscreen mode

Here, the code will run the 'free trial' first and then only after it has been run, will it check for the condition.
If the payment is less than 0, then terminate the program.


Summary

Loops are an essential tool in JavaScript that allows you to repeat a block of code multiple times, which can be very useful in a variety of situations. They can be used to iterate over the elements of an array, perform a task a certain number of times, repeat a task until a certain condition is met, or simplify repetitive code.


Hope you enjoyed this article ❤️

That's it! This was an introduction to JavaScript loops. Feel free to bookmark this if you'd like to come back at it in the future.

A new article on other types of loops is coming soon. If you are interested, you can follow me to get a notification when it's out :)

Let me know if you enjoyed it by leaving a like or a comment :) or if there is a topic that you'd like me to write about.

Thanks for your time,

Happy coding and Merry Christmas✨🎄🎅

. . . . . .