Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Array
  • JS String
  • JS Object
  • JS Operator
  • JS Date
  • JS Error
  • JS Projects
  • JS Set
  • JS Map
  • JS RegExp
  • JS Math
  • JS Number
  • JS Boolean
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
Open In App
Next Article:
JavaScript Iterator
Next article icon

JavaScript Iterator

Last Updated : 27 Dec, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Javascript Iterator is an object or pattern that allows us to traverse over a list or collection. Iterators define the sequences and implement the iterator protocol that returns an object by using a next() method that contains the value and is done. The value contains the next value of the iterator sequence and the done is the boolean value true or false if the last value of the sequence has been consumed then it's true else false. 

We can check if any entity is by default iterable or not We can check its prototype and can see if it is having a method Symbol(Symbol.iterator) or not. 

In Array.prototype you will find Symbol(Symbol.iterator): ƒ values() method. The array is by default iterable. Also, String, Map & Set are built-in iterables because their prototype objects all have a Symbol.iterator() method.

Example: This example uses the symbol.iterator approach to iterate over the array.

javascript
<script>     const array = ['a', 'b', 'c'];          const it = array[Symbol.iterator]();          // and on this iterator method we have ‘next’ method          console.log(JSON.stringify(it.next()));     //{ value: "a", done: false }          console.log(JSON.stringify(it.next()));     //{ value: "b", done: false }          console.log(JSON.stringify(it.next()));     //{ value: "c", done: false }          console.log(JSON.stringify(it.next()));     /* Actual it.next() will be { value: undefined,     done: true } but here you will get     {done: true} output because of JSON.stringify     as it omits undefined values*/ </script> 

Output:

{"value":"a","done":false}  {"value":"b","done":false}  {"value":"c","done":false}  {"done":true}

Using for.of loop, we can iterate over any entity (for eg: an object) which follows iterable protocol. The for.of loop is going to pull out the value that gets a return by calling the next() method each time.

Example: This example uses a for..of loop to iterate over the array.

javascript
<script>     const array = ['a', 'b', 'c'];     const it = array[Symbol.iterator]()     for (let value of it) {console.log(value)} </script> 

Output:

a  b  c

Iterable protocol: The object must define a method with 'Symbol.iterator' the key which returns an object that itself follows iterator protocol. The object must define the 'next' method which returns an object having two properties 'value' and 'done'

Syntax:

{value: 'item value', done: boolean}

Error scenario:

var newIt = arr[Symbol.iterator]    newIt()    //Because it does not properly bind  Uncaught TypeError: Cannot convert undefined or null to object   //How we can fix this   //var newIt = arr[Symbol.iterator].bind(arr);     newIt()  Array Iterator { }

Create our own iterable object:

javascript
<script>     var iterable = {     i: 0,     [Symbol.iterator]() {         var that = this;         return {         next() {             if (that.i < 5) {             return { value: that.i++, done: false }             } else {             return { value: undefined, done: true }             }         }         }     }     }          for(let value of iterable){console.log(value)} </script> 

Output:

0  1  2  3  4

Next Article
JavaScript Iterator

K

khandelwalsarthak31193
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • javascript-functions
  • JavaScript-Questions

Similar Reads

    Javascript String @@iterator Method
    String [@@iterator]( ) Method is used to make String iterable. [@@iterator]() returns an iterator object which iterates over all code points of String. String[@@iterator] is a Built-in Property of String. We can use this method by making a string iterator. We can make an iterator by calling the @@it
    2 min read
    JavaScript Symbol iterator Property
    It is an object of Iterables which is also a kind of generalized arrays. Iterables that make any object easier to use in a for..of the loop. We know that arrays are iterative in nature but other than that, there are also several objects which are used for the iterative purpose. Suppose if any object
    2 min read
    JavaScript Map.prototype[@@iterator]() Method
    Map[@@iterator]( ) method is used to make Map iterable. Map[@@iterator]( ) method returns iterator object which iterates over all code points of Map. Map[@@iterator]( ) is built-in property of Map. We can use this method by creating Map iterator. We can make Map iterator by calling the @@iterator pr
    2 min read
    TypeScript Array Symbol.iterator Method
    In TypeScript the Symbol.iterator function plays a role, in allowing iteration over arrays using for...of loops and other iterator-based mechanisms. This built-in function eliminates the need, for definition when working with arrays simplifying the process of accessing elements. Syntax:const iterato
    3 min read
    How to Create Custom Iterators and Iterables in JavaScript ?
    Iterators and Iterables are important concepts in the world of programming. They allow developers to traverse and manipulate collections of data in a more efficient and flexible way. JavaScript, being a high-level programming language, also supports iterators and iterables. In this article, we will
    6 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences