JavaScript Loops: A Comprehensive Guide
JavaScript offers various ways to iterate through loops. In this tutorial, we will explore each loop type with examples and discuss their main properties.
Introduction
JavaScript provides many ways to iterate through loops. This tutorial explains each one with a small example and highlights their unique features.
for
The for
loop is a commonly used loop in JavaScript. It allows you to iterate over a list of items by specifying the starting point, condition, and increment or decrement.
1 | const list = ['a', 'b', 'c']; |
You can interrupt a for
loop using break
, and you can skip to the next iteration using continue
.
forEach
The forEach
loop was introduced in ES5. It allows you to iterate over the properties of an array.
1 | const list = ['a', 'b', 'c']; |
Unfortunately, you cannot break out of this loop.
do...while
The do...while
loop executes a block of code at least once, and then repeats the loop while a specific condition is true.
1 | const list = ['a', 'b', 'c']; |
You can interrupt a while
loop using break
, and you can jump to the next iteration using continue
.
while
The while
loop executes a block of code as long as a specified condition is true.
1 | const list = ['a', 'b', 'c']; |
You can interrupt a while
loop using break
, and you can jump to the next iteration using continue
.
The difference with do...while
is that do...while
always executes its cycle at least once.
for...in
The for...in
loop iterates over all the enumerable properties of an object, giving the property names.
1 | for (let property in object) { |
for...of
The for...of
loop, introduced in ES6, combines the conciseness of forEach
with the ability to break.
1 | //iterate over the value |
Notice the use of const
. This loop creates a new scope in every iteration, so we can safely use const
instead of let
.
for...in
vs for...of
The main difference between for...in
and for...of
is that for...in
iterates over the property names of an object, whereas for...of
iterates over the property values.
Tags: JavaScript, Loops, forEach, for, while, do…while, for…in, for…of