4

I'm learning react from a book and in an example the author made a component render this way

return (
        <div className="star-rating">
        {[...Array(totalStars)].map((n,i)=>
            <Star key = {i} selected={i<starSelected} onClick={()=>this.change(i+1)} />
        )}
        <p>{starsSelected} of  {totalStars} stars </p>+
    )

What purpose does the spread element serve here when initializing the array?

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
Orca Prime
  • 155
  • 1
  • 1
  • 5

2 Answers2

3

Array(totalStars) makes an array with totalStars number of empty slots. Using the spread operator coerces the empty slots into undefined, effectively filling the array with SOMETHING to be mapped over (even if it is undefined).

Just instantiating an Array with Array() doesn't put anything in it's spaces, just allocates the space for them.

DillGromble
  • 383
  • 2
  • 8
  • cool, shorter than my current go to, which would be `Array.from({length:totalStars})` :p – Jaromanda X Aug 31 '17 at 02:41
  • 1
    It is a bit shorter, but Array.from is more semantic and a bit less hacky in my opinion. – DillGromble Aug 31 '17 at 02:48
  • Using the `Array` constructor with the `arrayLength` parameter doesn't actually allocate any memory for the "empty slots", it just sets the initial value for the `length` property. Arrays in JavaScript are sparse, meaning it will only allocate memory for indexes that have actually been set. – 4castle Aug 31 '17 at 02:52
  • Please [don't call it spread operator](https://stackoverflow.com/q/44934828/218196). – Felix Kling Aug 31 '17 at 04:45
-3

Spread operator means when we want things to be spread in form of array like -

function ABC (...) {

console. log(...); //this will print as array [1,3,5]

}

ABC(1,3,5);

When we make call to function, we are just passing as parameters not as array. But they coverted into form of Array with spread operators.

hardy
  • 880
  • 2
  • 13
  • 30