Since the introduction of iterator helpers in ECMAScript 2025, you can do:

Array(10).keys().forEach((_, i) => {
    console.log(i * 10);
});

This does not populate an array of the given length (as Array.from would do), and so the memory for it is constant, no matter what the provided length is for it. The forEachmethod here is not the Array method, but the Iterator method.


Note that if you just need a string repeated you can use String.prototype.repeat.

console.log("0".repeat(10))
// 0000000000
Answer from Tieme on Stack Overflow
🌐
DEV Community
dev.to › godcrampy › es6-for-loops-best-practices-4c86
ES6 for loops: Best Practices - DEV Community
August 25, 2019 - For loops are common control flow statements used to iterate over range, sequential data types etc. The ES6 revision of JavaScript provides several new features making the language more powerful, crisp and elegant.
🌐
Mozilla Hacks
hacks.mozilla.org › home › articles › es6 in depth: iterators and the for-of loop
ES6 In Depth: Iterators and the for-of loop – Mozilla Hacks - the Web developer blog
May 13, 2015 - Most astonishing of all, in some circumstances, this code can loop over the array elements in an arbitrary order. In short, for–in was designed to work on plain old Objects with string keys. For Arrays, it’s not so great. Remember last week I promised that ES6 would not break the JS code you’ve already written.
Discussions

Is there a mechanism to loop x times in ES6 (ECMAScript 6) without mutable variables?
We're getting really off-topic ... on to ES6 generators (or any other new, high level concept) is a good idea before they learn about mutable variables?:) ... Use let to declare that variable in the loop. Its scope ends with the loop. ... This does not populate an array of the given length (as Array.from would do), and so the memory for it is constant, ... More on stackoverflow.com
🌐 stackoverflow.com
Which way do you prefer to loop x times in ES6?
for Single iteration No additional objects needed Allows for infinite iterations Iteration count can be changed during iteration Can exit loop during any iteration with break Can be used with await for async iteration Can yield to parent iterator function Cannot be used in an expression context spread operator + forEach Iterates 2 times (spread, forEach) Creates 2 arrays (Array(), [...]) Limited to 4294967295 iterations Iteration count cannot be changed during iteration Cannot break out of loop (except through throw) Iteration is always synchronous (though callbacks can be async) Cannot yield to parent iterator function Exists as an expression resolving to undefined Array.from() Single iteration Creates 1 array plus requires an additional "from" array-like/iterable Limited to 4294967295 iterations Iteration count cannot be changed during iteration Cannot break out of loop (except through throw) Iteration is always synchronous (though mapper can be async) Cannot directly yield to parent iterator function though can participate in yielded values post iteration if delegated with yield* Exists as an expression resolving to array of values defined by mapper Recursion Single iteration No additional objects needed Limits iterations to allowed call stack depth Iteration count can be changed during iteration Can exit loop during any iteration with early return Iteration can be async Cannot directly yield to parent iterator function though can participate in yielded values during iteration if calls delegated with yield* Exists as an expression resolving to first function call return value More on reddit.com
🌐 r/learnjavascript
29
9
August 8, 2023
ES6 - Loop through objects of objects and mutate the object with additional properties
I’m trying to loop through the counties object of object and add two new properties(nameCombined & codeCombined) to the existing Keys (Bucks and Montgomery) I got up till here. But not able to ... More on stackoverflow.com
🌐 stackoverflow.com
Javascript for .. of loop (ECMAScript 6) - Stack Overflow
So new ECMAScript 6 has introduced for .. of loop syntax. Unfortunately, there aren't many documentations out there that explains what this really does. As in how it differs from using Array.prot... More on stackoverflow.com
🌐 stackoverflow.com
🌐
Exploring JS
exploringjs.com › es6 › ch_for-of.html
17. The for-of loop
for-of is a new loop in ES6 that replaces both for-in and forEach() and supports the new iteration protocol.
🌐
TutorialsPoint
tutorialspoint.com › es6 › es6_for_loop.htm
ES6 - for loop
The for loop executes the code block for a specified number of times. It can be used to iterate over a fixed set of values, such as an array. Following is the syntax of the for loop.
🌐
GeeksforGeeks
geeksforgeeks.org › javascript › es6-loops
ES6 Loops - GeeksforGeeks
April 27, 2023 - Definite: There are three types of Definite loops in ES6. Each of them is described below with the example: for( ; ; ) The for loop executes the code block for a specified number of times.
Top answer
1 of 16
426

Since the introduction of iterator helpers in ECMAScript 2025, you can do:

Array(10).keys().forEach((_, i) => {
    console.log(i * 10);
});

This does not populate an array of the given length (as Array.from would do), and so the memory for it is constant, no matter what the provided length is for it. The forEachmethod here is not the Array method, but the Iterator method.


Note that if you just need a string repeated you can use String.prototype.repeat.

console.log("0".repeat(10))
// 0000000000
2 of 16
189

OK!

The code below is written using ES6 syntaxes but could just as easily be written in ES5 or even less. ES6 is not a requirement to create a "mechanism to loop x times"


If you don't need the iterator in the callback, this is the most simple implementation

const times = x => f => {
  if (x > 0) {
    f()
    times (x - 1) (f)
  }
}

// use it
times (3) (() => console.log('hi'))

// or define intermediate functions for reuse
let twice = times (2)

// twice the power !
twice (() => console.log('double vision'))

If you do need the iterator, you can use a named inner function with a counter parameter to iterate for you

const times = n => f => {
  let iter = i => {
    if (i === n) return
    f (i)
    iter (i + 1)
  }
  return iter (0)
}

times (3) (i => console.log(i, 'hi'))


Stop reading here if you don't like learning more things ...

But something should feel off about those...

  • single branch if statements are ugly — what happens on the other branch ?
  • multiple statements/expressions in the function bodies — are procedure concerns being mixed ?
  • implicitly returned undefined — indication of impure, side-effecting function

"Isn't there a better way ?"

There is. Let's first revisit our initial implementation

// times :: Int -> (void -> void) -> void
const times = x => f => {
  if (x > 0) {
    f()               // has to be side-effecting function
    times (x - 1) (f)
  }
}

Sure, it's simple, but notice how we just call f() and don't do anything with it. This really limits the type of function we can repeat multiple times. Even if we have the iterator available, f(i) isn't much more versatile.

What if we start with a better kind of function repetition procedure ? Maybe something that makes better use of input and output.

Generic function repetition

// repeat :: forall a. Int -> (a -> a) -> a -> a
const repeat = n => f => x => {
  if (n > 0)
    return repeat (n - 1) (f) (f (x))
  else
    return x
}

// power :: Int -> Int -> Int
const power = base => exp => {
  // repeat <exp> times, <base> * <x>, starting with 1
  return repeat (exp) (x => base * x) (1)
}

console.log(power (2) (8))
// => 256

Above, we defined a generic repeat function which takes an additional input which is used to start the repeated application of a single function.

// repeat 3 times, the function f, starting with x ...
var result = repeat (3) (f) (x)

// is the same as ...
var result = f(f(f(x)))

Implementing times with repeat

Well this is easy now; almost all of the work is already done.

// repeat :: forall a. Int -> (a -> a) -> a -> a
const repeat = n => f => x => {
  if (n > 0)
    return repeat (n - 1) (f) (f (x))
  else
    return x
}

// times :: Int -> (Int -> Int) -> Int 
const times = n=> f=>
  repeat (n) (i => (f(i), i + 1)) (0)

// use it
times (3) (i => console.log(i, 'hi'))

Since our function takes i as an input and returns i + 1, this effectively works as our iterator which we pass to f each time.

We've fixed our bullet list of issues too

  • No more ugly single branch if statements
  • Single-expression bodies indicate nicely separated concerns
  • No more useless, implicitly returned undefined

JavaScript comma operator, the

In case you're having trouble seeing how the last example is working, it depends on your awareness of one of JavaScript's oldest battle axes; the comma operator – in short, it evaluates expressions from left to right and returns the value of the last evaluated expression

(expr1 :: a, expr2 :: b, expr3 :: c) :: c

In our above example, I'm using

(i => (f(i), i + 1))

which is just a succinct way of writing

(i => { f(i); return i + 1 })

Tail Call Optimisation

As sexy as the recursive implementations are, at this point it would be irresponsible for me to recommend them given that no JavaScript VM I can think of supports proper tail call elimination – babel used to transpile it, but it's been in "broken; will reimplement" status for well over a year.

repeat (1e6) (someFunc) (x)
// => RangeError: Maximum call stack size exceeded

As such, we should revisit our implementation of repeat to make it stack-safe.

The code below does use mutable variables n and x but note that all mutations are localized to the repeat function – no state changes (mutations) are visible from outside of the function

// repeat :: Int -> (a -> a) -> (a -> a)
const repeat = n => f => x =>
  {
    let m = 0, acc = x
    while (m < n)
      (m = m + 1, acc = f (acc))
    return acc
  }

// inc :: Int -> Int
const inc = x =>
  x + 1

console.log (repeat (1e8) (inc) (0))
// 100000000

This is going to have a lot of you saying "but that's not functional !" – I know, just relax. We can implement a Clojure-style loop/recur interface for constant-space looping using pure expressions; none of that while stuff.

Here we abstract while away with our loop function – it looks for a special recur type to keep the loop running. When a non-recur type is encountered, the loop is finished and the result of the computation is returned

const recur = (...args) =>
  ({ type: recur, args })
  
const loop = f =>
  {
    let acc = f ()
    while (acc.type === recur)
      acc = f (...acc.args)
    return acc
  }

const repeat = $n => f => x =>
  loop ((n = $n, acc = x) =>
    n === 0
      ? acc
      : recur (n - 1, f (acc)))
      
const inc = x =>
  x + 1

const fibonacci = $n =>
  loop ((n = $n, a = 0, b = 1) =>
    n === 0
      ? a
      : recur (n - 1, b, a + b))
      
console.log (repeat (1e7) (inc) (0)) // 10000000
console.log (fibonacci (100))        // 354224848179262000000

🌐
TutorialsPoint
tutorialspoint.com › home › es6 › es6 loops
Understanding ES6 Loops
January 23, 2017 - A loop whose number of iterations are definite/fixed is termed as a definite loop. The for loop is an implementation of a definite loop.
Find elsewhere
🌐
TutorialsPoint
tutorialspoint.com › es6 › es6_for_in_loop.htm
ES6 - for in loop
for (variablename in object) { statement or block to execute } In each iteration, one property from the object is assigned to the variable name and this loop continues till all the properties of the object are exhausted.
🌐
Reddit
reddit.com › r/learnjavascript › which way do you prefer to loop x times in es6?
r/learnjavascript on Reddit: Which way do you prefer to loop x times in ES6?
August 8, 2023 -

This question came to my mind when I had to render some random content a certain number of times and came up with four solutions. So I was wondering if I should choose one over the others, maybe for performance reasons.

Below are my approaches. Note that no index is needed, I just determine how many times to loop.

Using for:

for (let i = 0; i < 6; i++) {
  console.log("Repeat")
}

Using the spread operator:

[...Array(6)].forEach(() => {
  console.log("Repeat");
});

Using Array.from():

Array.from({ length: 6 }, () => {
  console.log("Repeat");
});

Using Recursion:

function repeat(num) {
  if (num === 0) return;
  console.log("Repeat")
  repeat(num - 1)
}

repeat(6);

So, are there any significant differences? If so, what are they? Or maybe some of you would take a completely different approach?

Thanks in advance.

Top answer
1 of 13
73
for Single iteration No additional objects needed Allows for infinite iterations Iteration count can be changed during iteration Can exit loop during any iteration with break Can be used with await for async iteration Can yield to parent iterator function Cannot be used in an expression context spread operator + forEach Iterates 2 times (spread, forEach) Creates 2 arrays (Array(), [...]) Limited to 4294967295 iterations Iteration count cannot be changed during iteration Cannot break out of loop (except through throw) Iteration is always synchronous (though callbacks can be async) Cannot yield to parent iterator function Exists as an expression resolving to undefined Array.from() Single iteration Creates 1 array plus requires an additional "from" array-like/iterable Limited to 4294967295 iterations Iteration count cannot be changed during iteration Cannot break out of loop (except through throw) Iteration is always synchronous (though mapper can be async) Cannot directly yield to parent iterator function though can participate in yielded values post iteration if delegated with yield* Exists as an expression resolving to array of values defined by mapper Recursion Single iteration No additional objects needed Limits iterations to allowed call stack depth Iteration count can be changed during iteration Can exit loop during any iteration with early return Iteration can be async Cannot directly yield to parent iterator function though can participate in yielded values during iteration if calls delegated with yield* Exists as an expression resolving to first function call return value
2 of 13
23
console.log("Repeat"); console.log("Repeat"); console.log("Repeat"); console.log("Repeat"); console.log("Repeat"); console.log("Repeat");
🌐
John Kavanagh
johnkavanagh.co.uk › home › articles › looping in modern javascript: foreach and for...of
Looping in JavaScript ES5 and ES6 : forEach and for...of
December 13, 2024 - Enter ES6, and the for...of method. Using the same example again: for (item of a) { console.log(item); if (item == 7) { break; }} For me, this looks even nicer than the ES5 forEach method. It's clear, concise, and allows you to set up a variable to be used inside the for loop clearly without having to pass it through as a parameter via function().
🌐
Ben Ilegbodu
benmvp.com › blog › learning-es6-for-of-loop
for-of loop | Ben Ilegbodu
The new for-of loop introduced with ES6 allows for iterating over an array (or any iterable) in a succinct fashion similar to how we can iterate over the keys of an object using for-in.
Top answer
1 of 1
6

You were on the right path with entries and forEach, but if you want to mutate the original object then map isn't what you want-- that is intended to both iterate over items in an array and, critically, return a new array. Instead, you can simply mutate the original in the body of your forEach, like so:

const counties = {
  "Bucks": {
        "countyCode": "42017",
        "globalStateCode": "PA",
        "stateCode": "PA"
    },
    "Montgomery": {
        "countyCode": "42091",
        "globalStateCode": "PA",
        "stateCode": "PA"
    }
};

Object.entries(counties).forEach(([countyName, county]) => {
  county.nameCombined = `${county.countyCode} (${county.stateCode})`;
  county.codeCombined = `${county.countyCode} ${county.stateCode} ${countyName}`;
});

console.log(counties);

Note you could get a bit cuter with destructuring to cut down on all of the county.someProperty above. Also worth noting-- be careful if you're mutating objects-- if you do it too liberally it can cause a real debugging nightmare.

EDIT

In response to the question in comments:

Why is [countyName, county] is in array notation?

The output of Object.entries(someObject) will be an array of arrays, in which the inner arrays consist of a property/key of the original object and the value. This is perhaps better understood via example:

const lumberjanes = {
   scientist: 'Jo',
   strategist: 'Mal',
   enforcer: 'April',
   archer: 'Molly',
   wildcard: 'Ripley',
};

console.log(Object.entries(lumberjanes));

/*
Logs:
[
  ['scientist', 'Jo'],
  ['strategist', 'Mal'],
  ...etc
]
*/

When we loop over that output, if we just write it as

Object.entries(lumberjanes)
    .forEach(entry => `Name: ${entry[1]}; Role: ${entry[0]}`);

we have to access the values by their index, which isn't very readable at a glance. If instead we can use destructuring to separate that parameter into named variables before we access them in the function body, like so:

Object.entries(lumberjanes)
    .forEach(([name, entry]) => `Name: ${name}; Role: ${entry}`);
🌐
GeeksforGeeks
geeksforgeeks.org › javascript › how-to-write-a-for-loop-in-es6
How to write a for loop in ES6 ? - GeeksforGeeks
July 23, 2025 - Here in this article, we will learn about different types of for loops. There are 3 types of For in ES6: for loop · for...in · for...of · 1. for( ; ; ): The for loop executes the code block for a specified number of times.
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Statements › for...of
for...of - JavaScript | MDN - MDN Web Docs
The for...of statement executes a loop that operates on a sequence of values sourced from an iterable object. Iterable objects include instances of built-ins such as Array, String, TypedArray, Map, Set, NodeList (and other DOM collections), as well as the arguments object, generators produced ...
🌐
Clubmate
clubmate.fi › the-new-es6-for-of-loop-with-javascript
The new ES6 for...of loop – clubmate.fi
It's an extremely capable loop that can iterate almost anything you give it. Basically, for...of iterates over the values of an array, not keys.
🌐
JavaScript Tutorial
javascripttutorial.net › home › javascript tutorial › javascript for…of loop
Introduction to JavaScript for...of Loop in ES6
October 6, 2023 - Home » JavaScript Tutorial » JavaScript for…of Loop · Summary: in this tutorial, you’ll how to use JavaScript for...of statement to iterate over iterable objects. ES6 introduced a new statement for...of that iterates over an iterable object ...
🌐
Jonathan Dempsey
jonathandempsey.dev › home › journal › javascript › javascript es6: the foreach() helper
JavaScript ES6: The forEach() Helper - Jonathan Dempsey
May 17, 2020 - forEach() is an ES6 helper that is used to call a function once on each item in an array. It’s iteration over an array or list. In ES5, if we wanted to iterate over an array, we would make use of a for loop.
🌐
Medium
alexandermgabriel.medium.com › es6-for-of-and-in-loops-f73cdad1c206
ES6 For Of and In Loops. During my time at my coding bootcamp, I… | by Alexander Gabriel | Medium
May 23, 2021 - During my time at my coding bootcamp, I learned and got pretty darn good at writing For loops. My understanding is that For loops iterate through an array and can perform an action on each element within the block of code. If I needed to hold onto a counter, or the index, of the element being iterated over, I would choose a For loop instead of a built-in method such as .map or .forEach.
🌐
Go Make Things
gomakethings.com › looping-through-arrays-the-es6-way
Looping through arrays the ES6 way | Go Make Things
July 27, 2017 - The traditional way of looping through arrays in vanilla JavaScript is with a for loop: var sandwiches = [ 'tuna', 'ham', 'turkey', 'pb&j' ]; for (var i = 0; i