Search code examples
javascriptarraysjavascript-objects

why it show empty object but still able to iterator?


let arr = [1, 2, 4]
let key = arr.keys();

console.log(key);

for (const k of key) {
  console.log(k);
}

I'm getting confuse when I try to console arr.keys() it show me undefined but if there is nothing in it then how we can able to iterate that object that show me 0 1 2.


Solution

  • it does not show undefined it shows

    Object [Array Iterator] {}, its not undefined but a iterator object when you do arr.keys() it simply makes an iterator of keys [0,1,2], in case of Simple integer or string arrays, index work as keys for example

    const array = [34,45,67,89]
    console.log(array[2]) // will print 67 as in current array at key 2 position it contains 67 value
    

    if you want to print keys instead of iterator object you can use this code sample

    let arr = [1,2,4]
    let key = arr.keys();
    console.log(key); // will print iterator object i.e Object [Array Iterator] {}
    console.log([...key])  //shows [0,1,2], iterator is converted to simple array which you can print