Here's an approach using generators:
function* square(n) {
for (var i = 0; i < n; i++ ) yield i*i;
}
Then you can write
console.log(...square(7));
Another idea is:
[...Array(5)].map((_, i) => i*i)
Array(5)
creates an unfilled five-element array. That's how Array
works when given a single argument. We use the spread operator to create an array with five undefined elements. That we can then map. See http://ariya.ofilabs.com/2013/07/sequences-using-javascript-array.html.
Alternatively, we could write
Array.from(Array(5)).map((_, i) => i*i)
or, we could take advantage of the second argument to Array#from
to skip the map
and write
Array.from(Array(5), (_, i) => i*i)
A horrible hack which I saw recently, which I do not recommend you use, is
[...1e4+''].map((_, i) => i*i)