DEV Community

Discussion on: Understanding Iterables & Iterators in javascript -ES6

Collapse
 
chenge profile image
chenge

Add js after 3 symbols to colr.

const array = ['one','two','three']  

// Array is a data source because it implements an iterator.  
console.log(typeof array[Symbol.iterator]) // function  

// We first get the iterator which allow us to iterate (i.e. consume) over the array values.  
const iterator = array[Symbol.iterator]()  

// The iterator follows the protocol of being an object with the 'next' function.  
console.log(typeof iterator.next) // function  

// Calling .next() returns the next element in the iteration.  
console.log(iterator.next()) // { value: 'one', done: false }  
console.log(iterator.next()) // { value: 'two', done: false }  
console.log(iterator.next()) // { value: 'three', done: false }  

// Until there's no more elements to iterate, which then returns 'done' as true.  
iterator.next() // { value: undefined, done: true }