Sunday, January 13, 2019

Understanding Iterables & Iterators in javascript -ES6

In this tutorial we are going to learn how to use Iterables & Iterators in javascript application. It is a very easy topic and here in this example,  we will provide you complete details on Iterables & Iterators. 

Iterable — described by a data structure that provides a way to expose its data to the public. This is done by implementing a method whose key is Symbol.iterator. Symbol.iterator is a factory of iterators.
Iterator — described by a structure that contains a pointer to the next element in the iteration.

Understanding Iterables & Iterators in javascript -ES6

Let's see the below example where we are extracting values from the array using iterator. Here in this example we are using next() function to get values from array one by one and it will return the result in object form.

Example 

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 }

Output :
----------------------------
> "function"
> "function"
> Object { value: "one", done: false }
> Object { value: "two", done: false }
> Object { value: "three", done: false }

Learn The Basics Of ES6 Generators - Javascript

This is all about Iterables & Iterators in javascript. Thank you for reading this article, and if you have any problem, have a another better useful solution about this article, please write message in the comment section.

No comments:

Post a Comment