DEV Community

Danish Saleem
Danish Saleem

Posted on

JavaScript for Beginners - Chapter 6: For and While loops

Today's chapter of JavaScript for beginners is all about loops. Super useful for iterating through data and executing the same function multiple times.

Looping

In code, you often need to repeat actions. Loops allows you to iterate through data (usually an array) and perform the same repeating action on each value. In this tutorial we will cover while and for loops, their syntax and how to use them.

While Loop

The while loop has the following syntax.

while (condition) {
  // Loop body
  // Code to executed goes here
}
Enter fullscreen mode Exit fullscreen mode

The code in the loop will continue to be executed while the condition is true.

let i = 0;

while (i < 3) {
  // Will output 0, then 1, then 2
  i++; // Increment i to move the loop on
}
Enter fullscreen mode Exit fullscreen mode

Do While Loop

In do while loop, the condition is moved below the loop.

do {
  // Loop body
  // Code to be executed goes here
} while (condition);
Enter fullscreen mode Exit fullscreen mode

This type of loop will execute the code and then check the condition. If it's true it will repeat.

let i = 0;

do {
  console.log(i);
  // Will output 0, then 1, then 2
  i++; // Increment i to move the loop on
} while (i < 3);
Enter fullscreen mode Exit fullscreen mode

Use Case

While loops are used when the code needs to repeat an unkown number of times.

let randomResult = 0;
let loopCount = 0;

while (randomResult !== 5) {
  // Generate a random number between 1 - 5
  randomResult = Math.floor(Math.random() * 6) + 1;
  // Increment loopCount
  loopCount++;
}

console.log(`The random result: ${randomResult}`);
// Output: The random result: 5
console.log(`The random loops: ${loopCount}`);
// Output: The random loops: 4
Enter fullscreen mode Exit fullscreen mode

For Loop

The for loop is a little more complex but also the most commonly used.

for (begin; condition; step) {
  // Loop body
  // Code to be executed goes here
}
Enter fullscreen mode Exit fullscreen mode

The for loop is made up of four parts.

Begin

i = 0 // Executes once upon entering the loop.

Condition

i < 3 // Checked before every loop iteration. If false, the loops stop.

Body

console.log(i) // Runs again and again while the condition is true.

Step

i++ // Executes after the body on each iteration.

Use Case

For loops are typically used when the number of iterations is known before entering the loop.

let fishInPond = 6;

for (let i = 0; i < fishInPond; i++) {
  console.log("You caught a fish!");
}

console.log("There are no fish left in the pond!");

// Output: You caught a fish! - First iteration
// Output: You caught a fish! - Second iteration
// Output: You caught a fish! - Third iteration
// Output: You caught a fish! - Fourth iteration
// Output: You caught a fish! - Fifth iteration
// Output: You caught a fish! - Sixth iteration
// There are no fish left in the pond!
Enter fullscreen mode Exit fullscreen mode

Foreach

If you're working with arrays, you can also use the foreach method - which is used for looping through arrays. The method calls a function for each element in the array, in order.

const lifeRoutine = ["Eat", "Sleep", "Code"];

lifeRoutine.forEach((lifeRoutine) => console.log(lifeRoutine));

// Output: Eat
// Output: Sleep
// Output: Code
Enter fullscreen mode Exit fullscreen mode

Summary

  • While loops are used when the number of iterations is unknown.
  • A do while loop moves the condition below the loop.
  • A for loop is used when the number of iterations is known.
  • When iterating through an array, a foreach loop can be used instead.
  • It's possible to create an infinite loop so think through your conditions carefully!

Let's connect 💜

You can follow me on Twitter, Instagram & GitHub

If you like this post. Kindly support me by Buying Me a Coffee

Buy Me a Coffee

Discussion (0)