JavaScript supports several types of loops that allow you to execute a block of code repeatedly. Here are explanations for the seven main types of loops in JavaScript.
-
for loop:
The
for
loop is used when you know the number of iterations beforehand. It consists of three optional parts: initialization, condition, and iteration statement.for (let i = 0; i < 5; i++) { // Code to be executed in each iteration }
-
while loop:
The
while
loop is used when the number of iterations is not known in advance. It continues executing the block of code as long as the specified condition is true.let i = 0; while (i < 5) { // Code to be executed in each iteration i++; }
-
do-while loop:
Similar to the
while
loop, thedo-while
loop executes the block of code at least once before checking the condition. It continues executing as long as the condition is true.let i = 0; do { // Code to be executed in each iteration i++; } while (i < 5);
-
for...in loop:
The
for...in
loop is used to iterate over the enumerable properties of an object. It assigns each property key to a variable in each iteration.const object = { a: 1, b: 2, c: 3 }; for (const key in object) { // Code to be executed for each property in the object }
-
for...of loop:
The
for...of
loop iterates over the values of an iterable object, such as an array, string, or other iterable. It assigns each value to a variable in each iteration.const array = [1, 2, 3, 4, 5]; for (const element of array) { // Code to be executed for each element in the array }
-
forEach loop (Array method):
The
forEach
method is a loop specifically for arrays. It iterates over each element of an array and executes a provided function for each.const array = [1, 2, 3, 4, 5]; array.forEach(function(element) { // Code to be executed for each element in the array });
-
map loop (Array method):
The
map
method is another array method that creates a new array by applying a function to each element of the original array.const array = [1, 2, 3, 4, 5]; const newArray = array.map(function(element) { // Code to transform each element return transformedValue; });