JavaScript object iterator and "..." | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

JavaScript object iterator and "..."

Hello, I was looking for way how to make range function in js and I found this: "...Array(5).keys()" I was trying to figure out what does it mean, so I loged keys() and it returned object iterator, so my question is, what is it and why it doesn't return array? Those 3 dots than make array from it Re: those 3 dots iterate trough it

13th Aug 2021, 7:14 AM
nicolas turek
nicolas turek - avatar
2 Answers
+ 2
You're familiar with the range function from Python and want something like it in JavaScript, right? JavaScript lets you define generators which work like generators from Python. Here is a range function that is similar to Python's except calling this range like range(5) won't do what you expect from Python. You'd have to pass more parameters to this one for a similar effect. function* range(start = 0, end = 100, step = 1) { let iterationCount = 0; for (let i = start; i < end; i += step) { iterationCount++; yield i; } return iterationCount; } for (var j of range(0, 5)) { console.log(j); } You could use the spread operator(...) with this range generator too. The Array(5) creates an Array with 5 empty elements in it. The keys method returns the keys from the Array. Since the 5 array indexes would be in the range of 0,1,2,3,4, keys() returns an iterator for [0,1,2,3,4]. keys() doesn't return an Array. An iterator is also what the above generator produces.
15th Aug 2021, 2:32 PM
Josh Greig
Josh Greig - avatar
0
Thanks, and yeah, it's idea from python, I mostly use for (let i = 0; i < number; i++) which is quite effective and simple usable in any case
26th Aug 2021, 4:13 PM
nicolas turek
nicolas turek - avatar