How to get sequence number in loops with JavaScript?

To get sequence numbers in loops with JavaScript, you can use various approaches. The most common method is maintaining a counter variable that increments with each iteration.

Using forEach() with External Counter

The forEach() method provides an elegant way to iterate through arrays while maintaining sequence numbers using an external counter:

let studentDetails = [
    {
        id: 101, 
        details: [{name: 'John'}, {name: 'David'}, {name: 'Bob'}]
    },
    {
        id: 102, 
        details: [{name: 'Carol'}, {name: 'David'}, {name: 'Mike'}]
    }
];

var counter = 1;
studentDetails.forEach(function(k) {
    k.details.forEach(function(f) {
        console.log("Sequence:", counter++, "Name:", f.name);
    });
});
Sequence: 1 Name: John
Sequence: 2 Name: David
Sequence: 3 Name: Bob
Sequence: 4 Name: Carol
Sequence: 5 Name: David
Sequence: 6 Name: Mike

Using forEach() with Index Parameter

The forEach() method also provides an index parameter that can serve as a sequence number:

let numbers = [10, 20, 30, 40, 50];

numbers.forEach(function(value, index) {
    console.log("Sequence:", index + 1, "Value:", value);
});
Sequence: 1 Value: 10
Sequence: 2 Value: 20
Sequence: 3 Value: 30
Sequence: 4 Value: 40
Sequence: 5 Value: 50

Using Traditional for Loop

Traditional for loops naturally provide sequence numbers through their index:

let fruits = ['Apple', 'Banana', 'Orange'];

for (let i = 0; i < fruits.length; i++) {
    console.log("Sequence:", i + 1, "Fruit:", fruits[i]);
}
Sequence: 1 Fruit: Apple
Sequence: 2 Fruit: Banana
Sequence: 3 Fruit: Orange

Comparison of Methods

Method Automatic Index Best For
forEach() with counter No Nested loops, complex sequences
forEach() with index Yes Simple arrays, functional style
Traditional for loop Yes Performance-critical code

Conclusion

Use external counters for complex nested loops, or leverage the built-in index parameter in forEach() for simpler cases. Traditional for loops remain the most straightforward approach for sequence numbering.

Updated on: 2026-03-15T23:18:59+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements