About Lesson
JavaScript Loops
Loops are a fundamental concept in programming that allow you to repeatedly execute a block of code.
Types of Loops in JavaScript:
-
for
Loop:- Syntax:
JavaScript
for (initialization; condition; increment/decrement) { // Code to be executed repeatedly }
- Example:
JavaScript
for (let i = 0; i < 5; i++) { console.log(i); // Output: 0 1 2 3 4 }
- Syntax:
-
while
Loop:- Syntax:
JavaScript
while (condition) { // Code to be executed repeatedly }
- Example:
JavaScript
let i = 0; while (i < 5) { console.log(i); i++; }
- Syntax:
-
do...while
Loop:- Syntax:
JavaScript
do { // Code to be executed repeatedly } while (condition);
- Example:
JavaScript
let i = 0; do { console.log(i); i++; } while (i < 5);
- Syntax:
-
for...of
Loop:- Iterates over the elements of an iterable object (like an array).
- Syntax:
JavaScript
for (const element of iterable) { // Code to be executed for each element }
- Example:
JavaScript
const fruits = ["apple", "banana", "orange"]; for (const fruit of fruits) { console.log(fruit); }
-
for...in
Loop:- Iterates over the properties of an object.
- Syntax:
JavaScript
for (const property in object) { console.log(property, object[property]); }
Key Considerations:
- Choose the Right Loop: Select the appropriate loop type based on your specific needs and the structure of your data.
- Loop Conditions: Ensure that the loop condition will eventually become false to avoid infinite loops.
- Break and Continue: Use the
break
statement to exit a loop prematurely and thecontinue
statement to skip the current iteration and move to the next.
Loops are essential for performing repetitive tasks in JavaScript, such as iterating over arrays, processing data, and generating patterns.