0
[...Array(product.countInStock).keys()].map((x) => (
   <option key={x + 1} value={x + 1}>
       {x + 1}
   </option>
))

what is the is the use of keys() is it like the key for value we get from the spread of array? please help me understand this snippet of code.

Julian
  • 33,915
  • 22
  • 119
  • 174
naveed
  • 111
  • 8
  • Array(someInt) creates an empty array with length someInt. with Array(someInt).keys() you will get an Iterator Object for that array. ...Array(someInt).keys() will destructure the Iterator you get from keys(). Finally, [...Array(someInt).keys()] will create an Array filled with integers in ascending order and length of someInt, starting with zero. – NickG Apr 06 '21 at 14:36
  • 1
    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/keys – basic Apr 06 '21 at 14:39
  • oh ok so its like giving all elements and index number right?? – naveed Apr 06 '21 at 14:42
  • yes, something like that – NickG Apr 06 '21 at 14:46

1 Answers1

2

This is an overly clever way to generate a range of numbers, which is something better built in to other programming languages.

To break it down, we'll assume a product.countInStock value of 5:

Array(5) creates a new array using the Array constructor of length 5, note that this just sets the length, and leaves all the values as empty. Chrome even logs this as [empty × 5]

Calling .keys() returns an iterator, which lets you iterate over the key values. Important thing at this step is it doesn't return an actual array, you have to spread or loop over the iterator to get the values.

The spreading is done with the [...iterator] piece, the result of [...Array(5).keys()] evaluates to [0,1,2,3,4], and from there it can be treated as a normal array with calls like map.

This Stack Overflow answer goes over it more and has some alternatives.

  • i makes a bit more sense now but still can u please tell me what does the keys() exactly do?? – naveed Apr 06 '21 at 14:38
  • 1
    You can read on it here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/keys Basically you get an array iterator object by calling .keys (on an array). You can think of it as something like a json object that looks like this: {0:undefined, 1:undefined, 2:undefined, 3:undefined, 4:undefined, 5:undefined} – NickG Apr 06 '21 at 14:43
  • it has started to make sense now thanks alot now i am getting whats going on thank you – naveed Apr 06 '21 at 14:45