JavaScript Loops

JavaScript Loops

JavaScript loops making you loopy? Read this!

ยท

2 min read

Table of contents

No heading

No headings in the article.

JavaScript Supports different kinds of loops:

  • for - loops through a block of code several times

  • for/in - loops through the properties of an object

  • for/of - loops through the values of an iterable object

  • while - loops through a block of code while a specified condition is true

  • do/while - also loops through a block of code while a specified condition is true

<iframe src="https://giphy.com/embed/MDXomrcGshGso" width="480" height="270" class="giphy-embed"></iframe>

[via GIPHY](https://giphy.com/gifs/loop-shrek-MDXomrcGshGso)

In JavaScript, loops are used to repeat a block of code multiple times, based on a certain condition. There are several types of loops in JavaScript:

  1. for loops: These loops are used to iterate over a block of code a specified number of times. The for loop has three components: the initializer, the condition, and the iterator. The initializer is executed once at the beginning of the loop and sets the starting value for the loop variable. The condition is evaluated before each iteration, and if it is true, the loop continues, otherwise, the loop stops. The iterator is executed after each iteration and updates the loop variable.
Copy codefor (let i = 0; i < 5; i++) {
  console.log(i);
}
  1. while loops: These loops are used to repeat a block of code as long as a certain condition is true. The condition is evaluated before each iteration, and if it is true, the loop continues, otherwise, the loop stops.
Copy codelet i = 0;
while (i < 5) {
  console.log(i);
  i++;
}
  1. do-while loops: These loops are similar to while loops, but the block of code is executed at least once before the condition is checked.
Copy codelet i = 0;
do {
  console.log(i);
  i++;
} while (i < 5);
  1. for-in loops: These loops are used to iterate over the properties of an object. It allows you to iterate over the properties of an object and access the property values.
Copy codelet obj = { a: 1, b: 2, c: 3 };
for (let key in obj) {
  console.log(key + ': ' + obj[key]);
}
  1. for-of loops: These loops are used to iterate over the values of an iterable, such as an array or a string.
Copy codelet arr = [1, 2, 3, 4, 5];
for (let value of arr) {
  console.log(value);
}

It is important to use the right loop for the task at hand and also be mindful of the loop's condition and the iterator, to avoid infinite loops or other performance issues.

Let me know your thoughts in the comments below!
Bye, for now! ๐Ÿ‘‹ Diki

ย