Loops in JavaScript
What Are Loops? Loops are used to execute a block of code repeatedly until a condition is no longer satisfied or the loop is otherwise stopped. For example, if we want to print numbers from 1 to 10, we don't need to write ten separate console.log() statements. We can use a loop instead. JavaScript provides different types of loops. Let's understand the most common ones. 1. for Loop A for loop is…
Loops in JavaScript are used to execute a block of code repeatedly until a specific condition is met or the loop is terminated. They prove useful when you want to print numbers, process arrays, perform calculations, or repeat tasks without duplicating code.
The most common types of loops in JavaScript include for, while, do...while, for...of, and for...in.
The for loop is employed when the number of repetitions is known beforehand. It comprises three parts: initializing a counter, setting a condition for the loop to continue, and incrementing or decrementing the counter. For example, the loop: for (let i = 1; i <= 5; i++) { console.log(i); } prints numbers from 1 to 5.
The while loop repeats as long as its condition remains true. It starts with a counter or any other variable before the loop and updates it within the loop. For instance, this loop: let i = 1; while (i <= 5) { console.log(i); i++; } also prints numbers from 1 to 5, but the counter is declared and updated inside the loop.
The do...while loop, on the other hand, executes the code block at least once before checking the condition. In the example: let i = 1; do { console.log(i); i++; } while (i <= 5); it prints numbers from 1 to 5, even if the condition is initially false.
The for...of loop is used to iterate over the values of an iterable, such as an array or string. For example: let fruits = ["Apple", "Banana", "Mango"]; for (let fruit of fruits) { console.log(fruit); } outputs "Apple", "Banana", and "Mango".
Lastly, the for...in loop is utilized to iterate over the enumerable property keys of an object. With an object like let student = { name: "John", age: 22, course: "CSE" }; the loop: for (let key in student) { console.log(key, student[key]); } prints "name John", "age 22", and "course CSE". For arrays, the for...of loop is generally more suitable when you need to access each value.
Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.