Javascript Loop Control
Javascript Loop Control
Loop control in JavaScript refers to the mechanisms used to repeatedly execute a block of code as long as a specified condition is met. JavaScript provides several types of loops to help you iterate over data, repeat actions, or perform calculations.
1. Types of Loops
- for loop: Runs a block of code a specific number of times.
- while loop: Repeats as long as a condition is true.
- do...while loop: Executes the block of code at least once before checking the condition.
- for...in loop: Iterates over the properties of an object.
- for...of loop: Iterates over the elements of an iterable object like an array.
let i = 1
: Initializes the loop variablei
.i <= 5
: The loop runs whilei
is less than or equal to 5.i++
: Incrementsi
by 1 after each iteration.- The loop starts with
i = 1
. - As long as
i <= 5
, theconsole.log
statement executes. i++
increasesi
after each iteration.- The block inside
do
executes first. - The condition
i <= 5
is checked after execution. key
represents each property name.person[key]
accesses the value of the property.fruit
represents each element in thefruits
array.- The loop prints each fruit.
2. Loop Detailed Explanation With Examples
2.1. The for
Loop
The for
loop is commonly used for a known number of iterations.
Example: Print numbers from 1 to 5
for (let i = 1; i <= 5; i++) { console.log(i); }
Explanation:
2.2. The while
Loop
The while
loop continues as long as the condition is true.
Example: Print numbers from 1 to 5
let i = 1; while (i <= 5) { console.log(i); i++; }
Explanation:
2.3. The do...while
Loop
The do...while
loop ensures the code runs at least once, even if the condition is false.
Example: Print numbers from 1 to 5
let i = 1; do { console.log(i); i++; } while (i <= 5);
Explanation:
2.4. The for...in
Loop
The for...in
loop is used to iterate over the properties of an object.
Example: Iterate through an object's properties
let person = { name: "Alice", age: 25, city: "New York" }; for (let key in person) { console.log(`${key}: ${person[key]}`); }
Explanation:
2.5. The for...of
Loop
The for...of
loop iterates over iterable objects like arrays, strings, or NodeLists.
Example: Iterate through an array
let fruits = ["Apple", "Banana", "Cherry"]; for (let fruit of fruits) { console.log(fruit); }
Explanation:
4. Summary
JavaScript loops and control statements are powerful tools for automating repetitive tasks, iterating over data, and managing flow within loops. By combining the different types of loops with break
and continue
, you can create efficient and readable logic in your programs.