user14696845
user14696845

Reputation: 3

How does this range function from the MDN docs work?

The MDN docs describe the Array.from() syntax as such;

// Arrow function
Array.from(arrayLike, (element) => { ... } )
Array.from(arrayLike, (element, index) => { ... } )
Array.from(arrayLike, (element, index, array) => { ... } )

It also provides an example range function like this;

  const range = (start, stop, step) => Array.from({ length: (stop - start) / step + 1}, (_, i) => start + (i * step));

I'm trying to understand exactly how this code works and I'm confused about two things:

1.) How is the { length: (stop - start) / step + 1} functioning as an arrayLike object here? Wouldn't that just result in a an object {length: number} ?

2.) What's going on with the _ in the (_, i) passed in as the index?

Upvotes: 0

Views: 188

Answers (2)

Unmitigated
Unmitigated

Reputation: 89384

  1. An array-like object just has a non-negative length property. For example, Array.from({length: 2}) returns [undefined, undefined].

  2. _ is the first parameter to the mapping callback (the previous element at the current index). It is meant to be ignored since there was no previously specified value. i is the index.
    The mapping callback transforms each element of the original array-like object to a new value in the output.

Upvotes: 1

apsillers
apsillers

Reputation: 115960

{ length: (stop - start) / step + 1} is "array-like" in that it has a length property.

The callback runs repeatedly for each nonnegative integer index less than the object's length. For each index, the callback is supplied as arguments

  1. Any value at that index on the input object, and
  2. The index itself

We don't care about the value at each index (indeed, the object doesn't have any), so we use _ to indicate we don't care about this parameter. (_ has no special significance in JavaScript, but it's just the author's way of hinting "this is a 'blank' and we don't care about it."). We only care about the index, supplied to the i parameter, which we use to compute an output value at that index.

Upvotes: 0

Related Questions