0

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?

0

2 Answers 2

1
  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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for clearing that up, I get it now.
@user14696845 Happy to help.
0

{ 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.

1 Comment

Thanks for the answer, that makes more sense now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.