Skip to content

JavaScript Loop For

Loops are a fundamental programming construct that allows you to execute a block of code repeatedly. This is particularly useful when you need to perform the same operation on multiple items or run code a specific number of times, often with varying values in each iteration.

Loops are essential for automating repetitive tasks. For example, when working with arrays:

// Without a loop, processing array items is repetitive:
let output = "";
const cars = ["BMW", "Volvo", "Saab", "Ford", "Fiat", "Audi"];
output += cars[0] + "\n";
output += cars[1] + "\n";
// ...and so on for all cars
// console.log(output); // This would print the first two cars

Loops provide a much more efficient and scalable way to handle such tasks.

JavaScript supports several kinds of loops:

  • for: Executes a block of code a specified number of times. Ideal for when you know the iteration count.
  • for...of: Iterates over the values of iterable objects like Arrays, Strings, Maps, Sets, etc. (Modern and preferred for arrays/strings).
  • for...in: Iterates over the enumerable properties (keys) of an object. Primarily used for objects, not arrays.
  • while: Loops through a block of code as long as a specified condition is true. The condition is checked before each iteration.
  • do...while: Similar to while, but the block of code is executed at least once before the condition is checked.
  • Array methods like forEach(), map(), filter(): Provide concise ways to iterate over and transform array elements (often covered in array-specific sections).

The traditional for loop is a versatile tool for creating loops, especially when you need fine-grained control over the iteration process (e.g., specific start/end points, custom increments).

The for loop has the following syntax:

for (initialization; condition; finalExpression) {
// code block to be executed as long as the condition is true
}

initialization (Statement 1): Executed once before the loop starts. Typically used to declare and initialize a loop counter variable (e.g., let i = 0).

condition (Statement 2): Evaluated before each loop iteration. If it’s true, the code block executes. If it’s false, the loop terminates.

finalExpression (Statement 3): Executed at the end of each loop iteration, after the code block. Usually used to increment or decrement the loop counter (e.g., i++, i--).

let textOutput = "";
for (let i = 0; i < 5; i++) {
textOutput += `The number is ${i}\n`;
}
console.log(textOutput);
/* Output:
The number is 0
The number is 1
The number is 2
The number is 3
The number is 4
*/

From the example above, you can read:

The initialization part (let i = 0;) declares a loop counter i and sets its initial value to 0. This happens only once.

The condition part (i < 5;) is checked before each iteration. As long as i is less than 5, the loop continues.

The finalExpression part (i++;) increments the value of i by 1 after each iteration’s code block is executed.

Typically, the initialization statement is used to declare and initialize a loop counter variable using let. For example, let i = 0;.

The initialization statement is optional. If omitted, you would typically initialize your loop variable before the loop begins.

You can declare and initialize multiple variables in the initialization statement, separated by commas. When declaring with let, each variable needs its own let if they are separate declarations, or use a single let for a comma-separated list.

const cars = ["Volvo", "BMW", "Mazda"];
let text = "";
// Initializing i and len. 'let' is used once for multiple declarations here.
for (let i = 0, len = cars.length; i < len; i++) {
text += cars[i] + "\n";
}
console.log(text);
/* Output:
Volvo
BMW
Mazda
*/

You can omit the initialization statement if your variables are set before the loop starts:

const cars = ["Volvo", "BMW", "Mazda", "Ford"];
let i = 1; // Variable initialized before the loop
const len = cars.length;
let text = "";
for (; i < len; i++) { // Initialization statement is omitted
text += cars[i] + "\n";
}
console.log(text);
/* Output:
BMW
Mazda
Ford
*/

The condition statement is evaluated before each iteration. It usually involves the loop counter and determines whether the loop should continue.

The condition statement is also optional.

If the condition evaluates to true (or a truthy value), the loop’s code block is executed. If it evaluates to false (or a falsy value), the loop terminates.

Caution: If you omit the condition statement, you must include a break statement somewhere within the loop’s code block to prevent an infinite loop. An infinite loop will cause your browser or program to hang. The break statement is covered in a later chapter.

The finalExpression is executed after each iteration of the loop’s code block. It’s commonly used to update the loop counter (e.g., i++, i += 2).

Like the other parts, the finalExpression is optional. You can perform the update logic within the loop’s code block if needed.

The finalExpression can perform various operations, such as decrementing (i--), incrementing by a larger step (i += 5), or even more complex expressions.

The final expression can also be omitted (like when you increment your values inside the loop):

const cars = ["Volvo", "BMW"];
let text = "";
let i = 0;
const len = cars.length;
for (; i < len; ) { // Final expression is omitted
text += cars[i] + "\n";
i++; // Counter incremented inside the loop body
}
console.log(text);
/* Output:
Volvo
BMW
*/

For iterating over iterable objects like arrays, strings, Maps, Sets, etc., the for...of loop provides a cleaner and more direct syntax. It iterates over the values of the iterable.

for (const variable of iterable) {
// code block to be executed for each value
}

Example with an array:

const colors = ["red", "green", "blue"];
let output = "";
for (const color of colors) {
output += color + "\n";
}
console.log(output);
/* Output:
red
green
blue
*/

Example with a string:

const message = "Hello";
for (const char of message) {
console.log(char);
}
/* Output:
H
e
l
l
o
*/

The for...of loop is generally preferred over the traditional for loop when you simply need to iterate through the elements of an array or other iterable without needing index access or complex initialization/increment logic.

The for…in Loop (Iterating Object Properties)

Section titled “The for…in Loop (Iterating Object Properties)”

The JavaScript for...in statement iterates over all enumerable property names (keys) of an object. It is primarily designed for iterating over the keys of an object.

for (const key in object) {
// code block to be executed for each property key
// 'object[key]' can be used to access the property's value
}

The block of code inside of the for...in loop will be executed once for each enumerable property key.

Looping through the properties of an object:

const person = {
fname: "John",
lname: "Doe",
age: 25
};
let info = "";
for (const key in person) {
// It's good practice to check if it's an own property
if (Object.hasOwnProperty.call(person, key)) {
info += `${key}: ${person[key]}\n`;
}
}
console.log(info);
/* Output (order may vary):
fname: John
lname: Doe
age: 25
*/
  • Order: The order of iteration over object properties is not strictly guaranteed for all types of keys or across all JavaScript engines, though modern engines often preserve insertion order for non-integer string keys.
  • Inherited Properties: for...in will also iterate over properties inherited from the object’s prototype chain. To iterate only over an object’s own properties, use Object.hasOwnProperty() within the loop, or use methods like Object.keys(), Object.values(), or Object.entries() combined with a for...of or forEach loop.
  • Use for Objects, Not Arrays: While you can use for...in with arrays (as arrays are objects), it’s generally not recommended. It will iterate over array indices as strings (e.g., “0”, “1”, “2”) and might also include any other enumerable properties added to the array object or its prototype. For arrays, use a traditional for loop, for...of, or array methods like forEach().

Example: Iterating own properties of an object using modern alternatives:

const car = { make: 'Toyota', model: 'Camry', year: 2021 };
console.log('Using Object.keys() and for...of:');
for (const key of Object.keys(car)) {
console.log(`${key}: ${car[key]}`);
}
/* Output:
make: Toyota
model: Camry
year: 2021
*/
console.log('\nUsing Object.entries() and for...of:');
for (const [key, value] of Object.entries(car)) {
console.log(`${key}: ${value}`);
}
/* Output:
make: Toyota
model: Camry
year: 2021
*/

The while loop and the do...while loop will be explained in the next chapter.