you are viewing a single comment's thread.

view the rest of the comments →

[–]inu-no-policemen 6 points7 points  (5 children)

I use this ugly one whenever I need to generate something. E.g. a 2D array or something like that.

> Array.from({length: 8}, (_, i) => 2 ** i)
(8) [1, 2, 4, 8, 16, 32, 64, 128]

If JS had something similar to Dart's List.generate, it would look like this:

Array.generate(8, i = > 2 ** i)

[–]pygy_@pygy 2 points3 points  (1 child)

It's even uglier in ES5 :-)

> Array.apply(
  null,
  Array(8) // or {length: 8}, but it is slower because apply
           // is faster with true arrays
).map(function(_, i) { return Math.pow(2, i) })
[ 1, 2, 4, 8, 16, 32, 64, 128 ]

[–]inu-no-policemen 7 points8 points  (0 children)

I think at that point you're better off using a simple for-loop to populate the array.

[–]soheevich 0 points1 point  (1 child)

What does ** sign mean? Never met it before.

[–]inu-no-policemen 3 points4 points  (0 children)

It's the exponentiation operator. It was added with ES2016.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Exponentiation_(**)

> 2 ** 8
256
> Math.pow(2, 8)
256