Definition and Usage
The for statement is a loop that repeats code a specific number of times or over a specified range.
It is very useful for repeatedly executing code a set number of times and is one of the essential basic loops you should know in JavaScript.
Basic Example
for (let i = 1; i <= 5; i++) {
console.log(i);
}
// Output: 1 2 3 4 5
This is a loop statement with an associated loop variable that has an initial value (let i = 1). It repeatedly executes a code block ({}) a specific number of times or over a specified range by comparing (i <= 5) and incrementing or decrementing (i++) the loop variable.
A loop variable is a variable used to control the number of iterations in a loop.
In the example above, i is the loop variable. i is initialized to 1, and the loop continues while the i <= 5 condition is satisfied. In each iteration, i is incremented by 1, and the loop ends when the condition is no longer satisfied.
Syntax
The for statement consists of three optional expressions enclosed in parentheses (()) and separated by semicolons (;), followed by a code block ({}).
for (initialization; condition; increment/decrement) {
// Code block to execute
}
initialization
This is the initialization expression. It sets the initial value of the loop variable. This expression is executed only once when the loop starts. It is optional.
A variable declared with the let keyword has block scope (local variable) within the loop.
condition
This is the condition expression that is evaluated against the loop variable to determine whether to execute the code block ({}). It is optional.
- If this condition evaluates to
true, the code block ({}) is executed. - If this condition evaluates to
false, theforstatement is no longer executed and terminates. - If this condition is omitted, it is considered to be
true. This results in an infinite loop. Therefore, you should be careful when omitting the condition expression. Unless you intentionally need to create an infinite loop, it is generally recommended not to omit the condition expression.
increment/decrement
After the code block ({}) is executed, the increment/decrement expression changes the value of the loop variable. It uses an operation to increment or decrement the loop variable so that the code can be repeated a specific number of times or over a specified range. It is optional.
Note!
The three optional expressions used here (initialization; condition; increment/decrement) can be omitted individually, but the semicolons (;) cannot be omitted.
Execution Order of the for Statement
When the for statement is executed, it follows the sequence below.
- If the initialization expression,
initialization, is not omitted,initializationis executed. - The
conditionis evaluated. If the condition evaluates totrue, the code block ({}) is executed. However, if it evaluates tofalse, theforstatement is no longer executed and terminates. If this condition is omitted, it is considered to betrue. - If the
conditionevaluates totrue, the code block ({}) is executed. - After the code block (
{}) is executed, ifincrement/decrementis not omitted, the value of the loop variable is changed usingincrement/decrement. - The process returns to the second step, where the
conditionis evaluated. The subsequent steps are repeated.
Practical Examples
The for statement is used to repeatedly execute code a specific number of times through a loop variable.
One of the major advantages of this loop statement is that you can also use the for statement to iterate over and access objects with components, such as arrays, array-like objects, and iterable objects.
This is a powerful feature that distinguishes it from other loop statements in JavaScript.
The following table summarizes the types of targets that can be iterated over by the major loop statements.
| Loop Statement | Iteration Targets |
|---|---|
for statement |
Code that repeats a specific number of times and index-accessible targets such as strings, arrays, and array-like objects |
for...in statement |
All enumerable property names (keys) of an object |
for...of statement |
Iterable objects in general (arrays, strings, Map, Set, etc.) |
forEach() function |
Dedicated iteration methods built into arrays, Map, and Set |
As you can see, the for statement can do more than other loop statements.
Let's look at how it is used in practice through the following examples.
Code That Repeats a Specific Number of Times
/* Print numbers from 1 to 10 */
for (let i = 1; i <= 10; i++) {
console.log(i);
}
// Output: 1 2 3 4 5 6 7 8 9 10
/* Print numbers from 10 to 1 */
for (let i = 10; i >= 1; i--) {
console.log(i);
}
// Output: 10 9 8 7 6 5 4 3 2 1
String Iteration
const text = "hello";
const textLength = text.length;
for (let i = 0; i < textLength; i++) {
console.log(text[i]);
}
// Output: "h" "e" "l" "l" "o"
Array Iteration
It is commonly used to iterate over each element of an array.
const fruits = ["apple", "banana", "cherry"];
const fruitsLength = fruits.length;
for (let i = 0; i < fruitsLength; i++) {
console.log(fruits[i]);
}
// Output: "apple" "banana" "cherry"
Code Explanation
The length property for arrays represents the number of elements contained in the array as a numeric value. An empty array has a length of 0.
Iterating Over Array-Like Objects
<ul>
<li>apple</li>
<li>banana</li>
<li>cherry</li>
</ul>
The querySelectorAll() function returns a NodeList object, which is array-like.
const listItems = document.querySelectorAll("li"); // NodeList, array-like
const listItemsLength = listItems.length;
for (let i = 0; i < listItemsLength; i++) {
console.log(listItems[i].textContent);
}
// Output: "apple" "banana" "cherry"
Syntax Examples
The following are examples related to the syntax of the for statement.
for Statement Without initialization
The initialization expression, initialization, can be omitted. Let's look at the following example.
let i = 0;
for (; i < 4; i++) {
console.log(i);
}
// Output: 0 1 2 3
for Statement Without condition
The condition can also be omitted. Let's look at the following example.
let i = 0;
for (; ; i++) {
if (i > 3) {
break;
}
console.log(i);
}
// Output: 0 1 2 3
Code Explanation
The break statement immediately terminates the current loop and transfers control to the code that follows it.
In this case, you need to take measures to prevent an infinite loop from occurring. In the example above, a conditional (if) statement and the break statement are used to prevent an infinite loop.
Things to Keep in Mind
There are several things to keep in mind when using the for statement.
Preventing Infinite Loops
For example, if the condition in a for statement always evaluates to true, it can result in an infinite loop. An infinite loop can cause the program to become unresponsive because the loop never terminates.
The following are some examples of for statements that cause infinite loops.
When the Condition Is Always True
for (let i = 0; i >= 0; i++) {
console.log(i); // Prints numbers continuously increasing from 0
}
When the Loop Variable Is Not Changed
for (let i = 1; i = 1; i++) {
console.log(i); // Continuously prints 1
}
When the condition Is Omitted Without Additional Measures
for (let i = 0; ; i++) {
console.log(i); // Infinite loop without a condition
}
When the condition Is Incorrect
for (let i = 0; i != 10; i--) {
console.log(i);
}
Repeatedly Checking the Array Length in the condition of a Loop
Checking the array length repeatedly in a loop is inefficient. Since the array length does not change, storing the length in a variable before entering the loop can avoid unnecessary operations on each iteration. This can improve performance.
For example, the following is not recommended.
const fruits = ['apple', 'banana', 'cherry'];
for (let i = 0; i < fruits.length; i++) { // Check fruits.length repeatedly
console.log(fruits[i]);
}
Use it as shown in the following example.
const fruits = ['apple', 'banana', 'cherry'];
const fruitsLength = fruits.length; // Check fruits.length only once
for (let i = 0; i < fruitsLength; i++) {
console.log(fruits[i]);
}
This way, fruits.length is checked only once, which can reduce resource usage.
Specifications
| Specification | |
|---|---|
for
|
ECMAScript® 2027 Language Specification #sec-for-statement |
Compatibility
| Statement |
Desktop Chrome
|
Desktop Edge
|
Desktop Firefox
|
Safari
|
Node.js
|
|---|---|---|---|---|---|
for
|
1 | 12 | 1 | 1 | 0.10 |