JavaScript For loop
Loops in JavaScript
In JavaScript, loops allow us to perform repetitive tasks efficiently. Instead of writing the same code over and over for each action, loops let us run a block of code multiple times, often with different values. Loops are especially helpful when working with arrays or large datasets where we need to perform the same operation on each item, such as calculating values, displaying items, or filtering data.
JavaScript Loop Types
JavaScript offers several types of loops, each suited for different tasks:
- for – Loops a set number of times based on a condition.
- for/in – Loops through the properties of an object.
- for/of – Loops through the values of an iterable object like an array.
- while – Loops while a specified condition is true.
- do/while – Similar to
while
, but guarantees at least one loop execution.
In this lesson, we’ll focus on the for loop, a commonly used loop type in JavaScript.
JavaScript for Loop
The for
loop in JavaScript is ideal for iterating a specific number of times. It consists of three expressions inside the parentheses:
- Expression 1: Initializes a variable, usually the loop counter.
- Expression 2: Sets the condition for the loop to run.
- Expression 3: Increments or modifies the counter at the end of each loop.
Syntax
1for (expression1; expression2; expression3) {
2 // Code to execute in each loop
3}
Example
Let’s say we want to display the numbers from 1 to 5:
1for (let i = 1; i <= 5; i++) {
2 console.log("Number: " + i);
3}
4// Outputs:
5// Number: 1
6// Number: 2
7// Number: 3
8// Number: 4
9// Number: 5
Here’s how each expression works in this loop:
- Expression 1 sets
i
to1
. - Expression 2 checks if
i
is less than or equal to 5. - Expression 3 increments
i
by 1 after each loop.
Expression in the for Loop
Expression 1: Initialization
Typically, Expression 1 initializes the loop variable, but it’s optional. You can set multiple variables here or leave it empty if variables are already defined.
Example:
1let start = 1;
2let end = 3;
3for (let i = start, message = "Counting: "; i <= end; i++) {
4 console.log(message + i);
5}
6// Outputs:
7// Counting: 1
8// Counting: 2
9// Counting: 3
Expression 2: Condition
Expression 2 defines the condition for the loop to continue. If this condition is false, the loop stops. If omitted, the loop runs infinitely, so always use a break
statement if you skip it.
Example:
1let count = 1;
2for (; count <= 3; count++) {
3 console.log("Count is: " + count);
4}
5// Outputs:
6// Count is: 1
7// Count is: 2
8// Count is: 3
Expression 3: Update
Expression 3 updates the loop variable. It can increment, decrement, or perform any other operation.
Example:
1for (let i = 10; i >= 0; i -= 2) {
2 console.log("Countdown: " + i);
3}
4// Outputs:
5// Countdown: 10
6// Countdown: 8
7// Countdown: 6
8// Countdown: 4
9// Countdown: 2
10// Countdown: 0
Using for Loop with Arrays
Loops are especially useful for working with arrays, allowing us to access each item by its index.
Example:
1const cities = ["New York", "London", "Tokyo"];
2for (let i = 0; i < cities.length; i++) {
3 console.log("City: " + cities[i]);
4}
5// Outputs:
6// City: New York
7// City: London
8// City: Tokyo
Working with Nested Loops
You can also use nested for
loops to handle multi-dimensional arrays or perform operations on multiple sets of data.
Example:
1const grid = [
2 [1, 2],
3 [3, 4],
4 [5, 6]
5];
6
7for (let i = 0; i < grid.length; i++) {
8 for (let j = 0; j < grid[i].length; j++) {
9 console.log("Value at grid[" + i + "][" + j + "]: " + grid[i][j]);
10 }
11}
12// Outputs each value in the grid
Variable Scope in for Loops: var vs let
Using var
in a loop creates a variable that exists outside the loop, while let
limits the variable’s scope to the loop itself.
Example with var
:
1var x = 10;
2for (var x = 0; x < 5; x++) {
3 console.log("Inside loop x: " + x);
4}
5console.log("Outside loop x: " + x); // Outputs: 5
Example with let
:
1let y = 10;
2for (let y = 0; y < 5; y++) {
3 console.log("Inside loop y: " + y);
4}
5console.log("Outside loop y: " + y); // Outputs: 10
Using let
keeps the loop variable contained within the loop, avoiding unintended changes outside the loop.
Tips for Using for Loops in JavaScript
- Use
for
loops for iterating a specific number of times or for processing arrays. - Expressions are flexible: You can skip or adjust any of the expressions as needed, but be careful to avoid infinite loops.
- Prefer
let
for block scope in loops to prevent variable leakage outside the loop. - Avoid Infinite Loops: Always ensure Expression 2 has a condition to stop the loop, or use a
break
statement if it’s omitted.