Author: M Abo Bakar Aslam
Loops
A loop in programming is a control structure that allows a set of instructions to be repeated multiple times based on a specified condition. Loops help automate repetitive tasks and efficiently process sequences of data. They are a fundamental part of almost all programming languages.
1. Types of Loops
JavaScript supports different kinds of loops:
- for - executes a block of code a specific number of times
- for/in - loops through the properties of an object
- for/of - loops through the values of an iterable object
- while - executes a block of code while a condition is true
- do/while - similar to while, but executes at least once
Loops are mostly used with arrays; therefore, many examples are based on arrays.
2. Loop for
The for loop consists of three optional expressions:
- Expression 1: Executes once before the loop starts
- Expression 2: Defines the condition for execution
- Expression 3: Executes after each iteration
Example Code 1
This example demonstrates iterating through an array and displaying each element.
//const is used to declared array
const cars = ["Saab", "Volvo", "BMW"]
//displaying each element by using loop
for(let i=0; i<cars.length; i++)
console.log(cars[i])2.1. Expression 1 in for Loop
Expression 1 is typically used to initialize variables, but it is optional.
- Multiple variables can be initialized
- It can be omitted if initialization is done earlier
Example Code 2
Demonstrates initializing multiple variables in the loop.
const cars = ["Saab", "Volvo", "BMW"]
//displaying each elment by using loop
for(let i=0, length=cars.length; i<length; i++)
console.log(cars[i])Example Code 3
Shows how to omit Expression 1 when variables are already initialized.
const cars = ["Saab", "Volvo", "BMW"]
//initialize values for loop
let i=0, length=cars.length
//no expression 1
for(; i<length; i++)
console.log(cars[i])Example Code 4
Demonstrates looping without knowing array length using an alternative for loop approach.
const cars = ["Saab", "Volvo", "BMW"];
let i=0
for (;cars[i];) {
console.log(cars[i])
i++
}2.2. Expression 2 in for Loop
Expression 2 defines the loop condition:
- If it evaluates to true, the loop continues
- If it evaluates to false, the loop stops
Important:
If Expression 2 is omitted, you must include a break statement to avoid an infinite loop.
Example Code 5
Demonstrates a loop without a condition, controlled using a break.
let j=0, v=10
for(;;j++){
console.log(j)
if(j==10)
break
}2.3. Expression 3 in for Loop
Expression 3 is usually used to update the loop variable:
- It can increment, decrement, or perform any operation
- It is optional and can be handled inside the loop
Example Code 6
Shows updating the loop variable within the loop body.
let j=5, v=20
for(;;){
console.log(j)
if(j==10)
break
j++
}3. Loop for in
The for...in loop iterates over the properties (keys) of an object.
- Works with objects, arrays, and dates
- Returns keys (indexes in arrays, property names in objects)
- No need to know the total number of elements
for (key in object) {
// code block to be executed
}Example Code 7
Demonstrates iterating over an object and displaying its keys.
Note: Only enumerable properties are included.
const person = {fname:"John", lname:"Doe", age:25}
for (let x in person) {
console.log(x) //only property's key would be displayed
}Example Code 8
Demonstrates using for...in with arrays (returns indexes).
Important:
Avoid using for...in when order matters in arrays. Use for or for...of instead.
const numbers = [45, 4, 9, 16, 25];
for (let x in numbers) {
console.log(x) //only array indexes (0,1,2,3,4,5) would be displayed
}4. Loop for of
The for...of loop iterates over values of iterable objects such as:
- Arrays
- Strings
- Maps
- NodeLists
Advantages:
- Simpler syntax compared to
for - Works with multiple iterable data structures
- Returns values instead of indexes
for (key of iterable) {
// code block to be executed
}Example Code 9
Demonstrates iterating over array values.
const numbers = [45, 4, 9, 16, 25];
for (let x of numbers) {
console.log(x)
}Example Code 10
Demonstrates iterating over characters in a string.
let courseName = "web development"
for (let x of courseName) {
console.log(x)// all letter of above string will be displayed in one column
}5. Loop while
The while loop executes as long as a condition remains true.
Example Code 11
Demonstrates a loop that runs while a variable is less than a specific value.
Important:
If the loop variable is not updated, it may result in an infinite loop.
let i=0
while (i < 10) {
console.log("value of i: ", i)
i++;
}6. Loop do while
The do...while loop is similar to while, but it guarantees at least one execution.
- Executes code first
- Then checks the condition
do {
// code block to be executed
}
while (condition)Example Code 12
Demonstrates a loop that executes at least once regardless of the condition.
let i=0
do {
console.log("value of i: ", i)
i++;
}
while (i < 10)Example Code 13
Shows iteration through an array without explicitly calculating its length.
Important:
Failure to update loop variables may cause infinite loops.
const cars = ["Saab", "Volvo", "BMW"];
let i=0
do{
console.log(cars[i])
i++
}
while(cars[i])7. Scope of Variables Used in Loop
Variable scope behaves differently depending on how variables are declared:
Using var
- Same memory is shared inside and outside the loop
- Variables can be redeclared
Example Code 14
Demonstrates how var affects scope and redeclaration.
var i=5
for(var i=0; i<10; i++){
console.log(i) //it will display values from 0 to 9
}
console.log(i) //it will display value 10 for variable iUsing let
- Separate memory is allocated inside and outside the loop
- Variables cannot be redeclared in the same scope
Example Code 15
Demonstrates block-level scope using let.
let i=5
for(let i=0; i<10; i++){
console.log(i) //it will display values from 0 to 9
}
console.log(i) //it will display value 5 for variable iRedeclaration Errors
Changing declaration types inside loops is not allowed and results in errors.
Example Code 16
Shows an error due to redeclaration using different keywords.
let i=5
for(var i=0; i<10; i++){
console.log(i)
}
console.log(i)Example Code 17
Another example demonstrating redeclaration errors.
Note: Proper understanding of loop structures and variable scope is essential for writing efficient and error-free JavaScript programs.
var i=5
for(let i=0; i<10; i++){
console.log(i)
}
console.log(i)