Iterable vs Enumerable

Video

JavaScript Notes

JavaScript
    // for… of loops vs for… in loops
    // for...in loops, go through enumerable properties (keys)
    // for...of loops, go through the iterator of the object (e.g. for Array or String objects) to get the values
    // iterable vs enumerable; 
    let log = console.log;
    let names = ['Gandalf', 'Bilbo', 'Aragorn', 'Gimli']; 
    names.elf = 'Legolas';
    Object.defineProperty(names, 'ent', 
                        {value: 'Treebeard', 
                        enumerable: false});
    
    let middleEarth = {
        'towns': ['Hobbiton', 'Rivendell'],
        'races': ['Elves', 'Hobbits', 'Men']
        middleEarth.creator = 'J.R.R. Tolkien';
        Object.defineProperty(middleEarth, 'age', 
                            {value: '3rd', 
                            enumerable: false});

    // Only String and Array Objects are iterable! 
    for (let p in names){
        log('in names', p);	        // will return indices of the array object, and name of the property ‘elf’, as the enumerable properties of the array object
    }
    log( );
    
    for (let p of names){
        log('of names', p);	        // will only return the values of the array, not the value of the property ‘elf’
    }
    log( );
    
    for (let p in middleEarth){
        log('in middleEarth', p);	// will return 'towns', 'races', and 'creator' as the enumerable properties of the generic object
    }
    log( );

    for (let p of middleEarth){
        log('of middleEarth', p);	// will return an error, as generic objects are not iterable!
    }
    log( );
    
    for (let p of middleEarth.towns){
        log('of middleEarth', p);	// will return values of the array middleEarth.towns
    }
    log( );
     
    for (let p of middleEarth.creator){
        log('of middleEarth', p);	// will return values, of the String object, ‘J.R.R. Tolkien’
    }
    log( );