2

Could someone explain how this [...Array(10).keys()]; working and logging 0 to 9 index?

console.log([...Array(10).keys()]);
MikeM
  • 13,156
  • 2
  • 34
  • 47
NewJS
  • 45
  • 6
  • 2
    Do you know what [`keys()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/keys) does? I am not sure what part you are not sure about. – epascarello Aug 24 '22 at 17:47
  • so you want the result to be [0,1,2,3,4,5,6,7,8,9] ? – Amaarockz Aug 24 '22 at 17:47
  • Well, you're not using the `num1` argument... – Heretic Monkey Aug 24 '22 at 17:48
  • @epascarello Yes i know how keys() works – NewJS Aug 24 '22 at 17:49
  • So it takes the iterator and converts it into an array. Still not sure what you are looking for in an answer. – epascarello Aug 24 '22 at 17:50
  • i want to know how that spread and key working together @Amaarockz – NewJS Aug 24 '22 at 17:50
  • That was typo mistake @HereticMonkey – NewJS Aug 24 '22 at 17:51
  • 2
    Keys returns an iterator that has the values of 0-9 and the spread takes the iterator and converts those values into an array. Quicker way of making an array for increasing numbers. https://stackoverflow.com/questions/3746725/how-to-create-an-array-containing-1-n – epascarello Aug 24 '22 at 17:52
  • keys() basically return the indices of the Array(10) as an iterator, the square brackets then converts the iterator into 'list'. learn more [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/keys] – pyzer Aug 24 '22 at 17:55

1 Answers1

1

Here is the explanation

Case-1

const string = 'hello';

const array = [...string];

array;
// [ 'h' , 'e', 'l', 'l', 'o' ]

Case-2

Where we see spread operator acting as an eraser

[
  ...[1, 2, 3] // The dots erases the brackets
]

/*  Becoming this: */
[
  1, 2, 3 // "Erased"
]

Combining both of the above cases will help you on whats happening

Amaarockz
  • 4,348
  • 2
  • 9
  • 27