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: Executes a set of statements repeatedly for a defined count.
- while loop: Continues execution while the specified condition remains true.
- do...while loop: Ensures the loop body runs at least once before evaluating the condition.
- for...in loop: Loops through an object's enumerable properties.
- for...of loop: Traverses each element in an iterable, such as an array or string.
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 ideal when the iteration count is predetermined.
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 runs repeatedly until the condition evaluates to false.
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 executes the code block once before evaluating the condition.
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 traverses an object's enumerable properties.
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.