- JS Introduction
- JS Introduction
- JS Comments
- JS Variables
- JS Datatypes
- JS Operators
- JS Type Conversions
- JS Control Flow
- JS Comparisons
- JS If else
- JS If else Ladder
- JS Ternary Operator
- JS Switch
- JS For Loop
- JS For In
- JS For Of
- JS While
- JS Do While
- JS Break & Continue
- JS Functions
- JS Function Declaration
- JS Function Parameters
- JS Return Statement
- JS Function Expressions
- JS Anonymous Functions
- JS Objects
- JS Objects
- JS Object Methods
- JS Object Constructors
- JS Object Destructuring
- JS Object Prototypes
- JS Map, Filter & Reduce
- JS ES6
- JS ES6
- JS let and const
- JS Arrow Functions
- JS Template Literals
- Destructuring Assignment
- JS Spread Operator
- JS Default Parameters
- JS Classes
- JS Inheritance
- JS Map
- JS Set
- JS Async
- JS Callbacks
- JS Asynchronous
- JS Promises
- JS Async/Await
- JS HTML DOM/BOM
- JS Document Object
- JS getElementbyId
- getElementsByClassName
- JS getElementsByName
- getElementsByTagName
- JS innerHTML
- JS outerHTML
- JS Window Object
- JS History Object
- JS Navigator Object
- JS Screen Object
JavaScript For Loop
The for loop is one of the most fundamental building blocks in JavaScript. It allows you to run a block of code repeatedly, which is essential for tasks like processing lists of data, generating UI elements, or performing calculations until a specific target is reached.
Key Points:
- The for loop is a control flow statement for executing code repeatedly in JavaScript, helping you follow the DRY (Don't Repeat Yourself) principle.
- It is specifically designed for scenarios where you know how many times you need to iterate, such as counting to a number or looping through an array.
- Syntax:
for (initialization; condition; increment/decrement) {
// Code to be executed in each iteration
}
- Initialization: This runs only once at the very beginning. It is typically used to declare a counter variable (usually named
i). - Condition: Evaluated before every loop iteration. If it evaluates to
true, the code inside the curly braces runs. If it'sfalse, the loop stops immediately. - Increment/Decrement: This runs at the end of every loop iteration. It updates your counter variable so that the loop eventually meets the exit condition.
- It is a versatile tool for iterating over arrays, strings, or any sequence of data.
- The break statement allows you to "jump out" of a loop entirely before it finishes naturally.
- The continue statement skips the current iteration and moves directly to the next step in the loop.
let to declare your counter variable (e.g., let i = 0). Using var can lead to scope-related bugs where the variable "leaks" outside of the loop.
Examples:
Basic Numeric Iteration:
The most basic use case is counting. This is helpful for generating repetitive HTML elements or simply tracking progress.
for (let i = 0; i < 5; i++) {
console.log("Iteration number: " + i);
}
This loop prints numbers from 0 to 4. Once i reaches 5, the condition i < 5 becomes false, and the loop terminates.
false (for example, if you forget to increment i), you will create an infinite loop, which can crash your browser or server.
Iterating Over an Array:
In real-world development, you’ll frequently use loops to process data fetched from an API or a database, usually stored in arrays.
const fruits = ['apple', 'banana', 'orange'];
for (let i = 0; i < fruits.length; i++) {
console.log("Processing: " + fruits[i]);
}
This loop iterates through each element in the fruits array by using the index i to access the current item.
i <= fruits.length instead of i < fruits.length. Because array indexes are zero-based, the last item is at length - 1. Using <= will try to access an index that doesn't exist, returning undefined.
Skipping Even Numbers:
Sometimes you don't need to process every item. The continue statement lets you filter items on the fly.
for (let i = 0; i < 10; i++) {
if (i % 2 === 0) {
continue; // If the number is even, skip the rest of this block
}
console.log("Odd number found: " + i);
}
This loop prints odd numbers from 0 to 9. When the loop hits an even number, it skips the console.log and moves to the next increment.
Breaking the Loop Early:
The break statement is useful for performance. If you are searching for a specific value in a large list, you should stop the loop as soon as you find it.
const users = ['Alice', 'Bob', 'Charlie', 'David'];
const target = 'Charlie';
for (let i = 0; i < users.length; i++) {
if (users[i] === target) {
console.log("Found " + target + " at index " + i);
break; // No need to check 'David', so we exit early
}
}
This loop prints numbers from 0 to 4 and exits when i becomes 5. In the practical example above, it saves resources by stopping the search once the match is found.
Nested Loop for Matrix Iteration:
Nested loops are used when dealing with multi-dimensional data, like grids, coordinates, or tables (arrays within arrays).
const matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
for (let i = 0; i < matrix.length; i++) {
// Inner loop handles the columns for each row
for (let j = 0; j < matrix[i].length; j++) {
console.log("Value at row " + i + ", col " + j + ": " + matrix[i][j]);
}
}
This nested loop iterates through each element in a 2D matrix. The outer loop handles the "rows," while the inner loop handles the "columns."
for loops are powerful, modern JavaScript often uses cleaner methods like .forEach(), .map(), or for...of for simple array iteration. Use the standard for loop when you need fine-grained control or the best possible performance for heavy computations.
These examples demonstrate the versatility of the for loop in various scenarios, including basic numeric iteration, array traversal, skipping specific values, and breaking out of the loop early. Understanding these patterns is key to writing efficient and logic-heavy JavaScript applications.