Is there a mechanism to loop x times in ES6 (ECMAScript 6) without mutable variables? Is there a mechanism to loop x times in ES6 (ECMAScript 6) without mutable variables? javascript javascript

Is there a mechanism to loop x times in ES6 (ECMAScript 6) without mutable variables?


Using the ES2015 Spread operator:

[...Array(n)].map()

const res = [...Array(10)].map((_, i) => {  return i * 10;});// as a one linerconst res = [...Array(10)].map((_, i) => i * 10);

Or if you don't need the result:

[...Array(10)].forEach((_, i) => {  console.log(i);});// as a one liner[...Array(10)].forEach((_, i) => console.log(i));

Or using the ES2015 Array.from operator:

Array.from(...)

const res = Array.from(Array(10)).map((_, i) => {  return i * 10;});// as a one linerconst res = Array.from(Array(10)).map((_, i) => i * 10);

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

console.log("0".repeat(10))// 0000000000


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 ittimes (3) (() => console.log('hi'))// or define intermediate functions for reuselet twice = times (2)// twice the power !twice (() => console.log('double vision'))