Search code examples
javascriptarraysiteratorsymbols

Why do you access Symbol.iterator via brackets?


If I created an array, for instance, var array=[1,2,3,4]; to return an iterator I would do var iterator = array[Symbol.iterator](); I don't understand why you access the Symbol.iterator property through brackets? Why isn't it just array.Symbol.iterator?


Solution

  • There is no property on an array called Symbol (unless you put one there). Instead you are looking up the values whose key is the symbol primitive that Symbol.iterator points to. Symbol.iterator returns a symbol and you use that symbol as the lookup key. It's a little like looking up a property with a variable:

    let a = [1, 2, 3]
    a.someProp = "hello"
    
    let key = "someProp"
    
    // this doesn't work for the same reason s.Symbol.iterator doesn't:
    // a.key
    
    // but this does:
    console.log(a[key])
    
    // So with a Symbol:
    
    let k = Symbol.iterator
    console.log(typeof k)
    // k is now a reference to the symbol that is the key
    // you can use that to returns the iterator function
    console.log(a[k])    // <-- that returns your iterator function
    console.log([...a[k]()])
    
    // equivalent to:
    console.log([...a[Symbol.iterator]()])