-
Hajipur, Bihar, 844101
Hajipur, Bihar, 844101
JS Basics
JS Variables & Operators
JS Data Types & Conversion
JS Numbers & Math
JS Strings
JS Dates
JS Arrays
JS Control Flow
JS Loops & Iteration
JS Functions
JS Functions
Function Definitions
Function Parameters
Function Invocation
Function Call
Function Apply
Function Bind
Function Closures
JS Arrow Function
JS Objects
JS Objects
JS Object Properties
JS Object Methods
JS Object Display
JS Object Constructors
Object Definitions
Object Get / Set
Object Prototypes
Object Protection
JS Classes & Modules
JS Async Programming
JS Advanced
JS Destructuring
JS Bitwise
JS RegExp
JS Precedence
JS Errors
JS Scope
JS Hoisting
JS Strict Mode
JS this Keyword
JS HTML DOM
DOM Intro
DOM Methods
DOM Document
DOM Elements
DOM HTML
DOM Forms
DOM CSS
DOM Animations
DOM Events
DOM Event Listener
DOM Navigation
DOM Nodes
DOM Collections
DOM Node Lists
JS BOM (Browser Object Model)
JS Web APIs
Web API Intro
Web Validation API
Web History API
Web Storage API
Web Worker API
Web Fetch API
Web Geolocation API
JS AJAX
AJAX Intro
AJAX XMLHttp
AJAX Request
AJAX Response
AJAX XML File
AJAX PHP
AJAX ASP
AJAX Database
AJAX Applications
AJAX Examples
JS JSON
JSON Intro
JSON Syntax
JSON vs XML
JSON Data Types
JSON Parse
JSON Stringify
JSON Objects
JSON Arrays
JSON Server
JSON PHP
JSON HTML
JSON JSONP
JS Graphics & Charts
Loops are essential in programming for executing a block of code repeatedly based on a condition. The for loop in JavaScript is one of the most commonly used loops, especially when the number of iterations is known in advance. It allows developers to write concise, readable, and maintainable code for repetitive tasks.
This tutorial explains the for loop in detail, provides practical examples, highlights common mistakes, and shares best practices for efficient use.
The for loop is important because it allows you to:
Automate repetitive tasks, such as processing items in an array.
Control the number of iterations explicitly.
Reduce code duplication.
Improve readability compared to writing the same code multiple times.
Combine with arrays, strings, and other iterable structures effectively.
Without loops, you would have to manually write repeated code blocks, which is inefficient and error-prone.
The basic syntax of a for loop is:
for (initialization; condition; increment/decrement) {
// Code to execute in each iteration
}
Initialization – Sets up a counter variable, executed once before the loop starts.
Condition – Evaluated before each iteration; if true, the loop continues.
Increment/Decrement – Updates the counter after each iteration.
for (let i = 0; i < 5; i++) {
console.log("Iteration number: " + i);
}
Output:
Iteration number: 0
Iteration number: 1
Iteration number: 2
Iteration number: 3
Iteration number: 4
Here, the loop starts with i = 0 and runs until i < 5. After each iteration, i is incremented by 1.
for (let i = 5; i > 0; i--) {
console.log("Countdown: " + i);
}
Output:
Countdown: 5
Countdown: 4
Countdown: 3
Countdown: 2
Countdown: 1
This demonstrates using the for loop to count backward by decrementing the counter.
The for loop is often used to iterate over arrays:
let fruits = ["Apple", "Banana", "Cherry"];
for (let i = 0; i < fruits.length; i++) {
console.log(fruits[i]);
}
Output:
Apple
Banana
Cherry
You can access array elements using the loop counter and perform operations on them.
for loops can be nested inside each other for multi-dimensional operations:
for (let i = 1; i <= 3; i++) {
for (let j = 1; j <= 2; j++) {
console.log(`i = ${i}, j = ${j}`);
}
}
Output:
i = 1, j = 1
i = 1, j = 2
i = 2, j = 1
i = 2, j = 2
i = 3, j = 1
i = 3, j = 2
Nested loops are useful for working with matrices or multi-level data structures.
let sum = 0;
for (let i = 1; i <= 10; i++) {
sum += i;
}
console.log("Sum of numbers 1 to 10: " + sum);
for (let i = 1; i <= 5; i++) {
console.log("*".repeat(i));
}
Output:
*
**
***
****
*****
let numbers = [10, 20, 30, 40];
for (let i = 0; i < numbers.length; i++) {
numbers[i] *= 2; // Double each value
}
console.log(numbers); // [20, 40, 60, 80]
for (let i = 1; i <= 10; i++) {
if (i % 2 === 0) continue; // Skip even numbers
console.log(i);
}
Output:
1
3
5
7
9
Forgetting to update the loop counter, resulting in an infinite loop.
Using the wrong comparison operator in the condition.
Accessing an array index out of bounds.
Overcomplicating nested loops without proper control.
Declaring the counter outside the loop unnecessarily.
Use let for loop counters to limit scope.
Avoid unnecessary nested loops if possible to reduce complexity.
Always ensure the loop condition will eventually become false.
Use .length dynamically for arrays instead of hard-coded values.
Consider for...of or array methods for cleaner iteration when appropriate.
Iterating through arrays or objects.
Calculating totals, averages, or summaries.
Generating patterns or reports.
Manipulating DOM elements in web applications.
Performing repeated tasks like animations or batch processing.
The for loop in JavaScript is a powerful and flexible tool for repeating code a known number of times. It provides control over initialization, conditions, and counter updates, making it ideal for iterating arrays, generating patterns, or performing calculations. By understanding its syntax, avoiding common mistakes, and following best practices, developers can use for loops effectively in a wide range of applications, from simple scripts to complex data processing tasks.
Q1. How do you print numbers from 1 to 10 using a for loop?
Q2. How can you loop through an array of strings using a for loop?
Q3. What is the role of the increment statement in a for loop?
Q4. How can you skip a particular iteration in a for loop using continue?
Q5. What happens if you forget to update the loop counter in a for loop?
Q6. How can you exit a for loop prematurely using break?
Q7. Write a for loop that prints only even numbers from 1 to 10.
Q8. How can you use a for loop to count backwards from 10 to 1?
Q9. Can you use a for loop to loop through a string’s characters? How?
Q10. Write a nested for loop to generate pairs like (1,1), (1,2), (2,1), (2,2).
JS Basics
JS Variables & Operators
JS Data Types & Conversion
JS Numbers & Math
JS Strings
JS Dates
JS Arrays
JS Control Flow
JS Loops & Iteration
JS Functions
JS Functions
Function Definitions
Function Parameters
Function Invocation
Function Call
Function Apply
Function Bind
Function Closures
JS Arrow Function
JS Objects
JS Objects
JS Object Properties
JS Object Methods
JS Object Display
JS Object Constructors
Object Definitions
Object Get / Set
Object Prototypes
Object Protection
JS Classes & Modules
JS Async Programming
JS Advanced
JS Destructuring
JS Bitwise
JS RegExp
JS Precedence
JS Errors
JS Scope
JS Hoisting
JS Strict Mode
JS this Keyword
JS HTML DOM
DOM Intro
DOM Methods
DOM Document
DOM Elements
DOM HTML
DOM Forms
DOM CSS
DOM Animations
DOM Events
DOM Event Listener
DOM Navigation
DOM Nodes
DOM Collections
DOM Node Lists
JS BOM (Browser Object Model)
JS Web APIs
Web API Intro
Web Validation API
Web History API
Web Storage API
Web Worker API
Web Fetch API
Web Geolocation API
JS AJAX
AJAX Intro
AJAX XMLHttp
AJAX Request
AJAX Response
AJAX XML File
AJAX PHP
AJAX ASP
AJAX Database
AJAX Applications
AJAX Examples
JS JSON
JSON Intro
JSON Syntax
JSON vs XML
JSON Data Types
JSON Parse
JSON Stringify
JSON Objects
JSON Arrays
JSON Server
JSON PHP
JSON HTML
JSON JSONP
JS Graphics & Charts
