JavaScript loops are fundamental constructs for performing repetitive tasks efficiently. They allow executing a code block repeatedly while a specific condition is true. Here are the main types of loops in JavaScript:
For Loop: The ‘for’ loop is used when the number of iterations is known.
Syntax: for (initialization; condition; increment/decrement { // code to be executed } Example: Print numbers from 1 to 5 using a for-loop for (let i = 1; i <= 5; i++) { console.log(i); }
while loop: The ‘while’ loop executes a code block if a specified condition is true.
Syntax: while(condition) { // code to be executed } Example: Print numbers from 1 to 5 using a while loop let i = 1; while (i <= 5) { console.log(i); i++; }
do...while loop: The ‘do...while’ loop is similar to the ‘while’ loop but ensures the code block is executed at least once before checking the condition.
Syntax: do { // code to be executed }while(condition) Example: Print numbers from 1 to 5 using a do...while loop let j = 1; do { console.log(j); j++; } while (j <= 5);
Syntax: for (variable in object) { // code to be executed } Example: Iterate over the properties of the person object using a for...in loop const person = { name: 'John', age: 30 }; for (let key in person) { console.log(key + ': ' + person[key]); }
Syntax: for (variable of iterable) { // code to be executed } Example: Iterate over the elements of the fruits array using a for...of loop const fruits = ['apple', 'banana', 'cherry']; for (let fruit of fruits) { console.log(fruit); }
Understanding JavaScript loops is essential for efficiently performing repetitive tasks in programming. Each loop type serves a specific purpose: iterating a known number of times with a ‘for’ loop, checking conditions with ‘while’ and ‘do...while’ loops, or iterating over object properties and iterable elements with ‘for...in’ and ‘for...of’ loops.
By mastering these loops, you can write cleaner, more efficient code, making your development process smoother and more effective. Practice using these loops in different scenarios to enhance your coding and problem-solving skills.