Skip to content
geeksforgeeks
  • 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
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • 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 Map.prototype[@@iterator]() Method
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 Map.prototype[@@iterator]() Method

K

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

Similar Reads

  • JavaScript typedArray.@@iterator
    The typedArray.@@iterator is an inbuilt property in JavaScript which is used to return the initial value of the given typedArray's element. Syntax: arr[Symbol.iterator]() Parameters: It does not accept any parameter because it is a property not a function. Return value: It returns the array iterator
    1 min read
  • 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
  • Are Objects Iterable in JavaScript?
    In JavaScript, plain objects are not iterable by default, meaning you cannot directly use constructs like for...of loops or the spread operator (...) with them. However, arrays (a), strings, maps, and sets are inherently iterable. Understanding Iterables in JavaScriptAn iterable is an object that im
    3 min read
  • JavaScript Map entries() Method
    JavaScript Map.entries() method is used for returning an iterator object which contains all the [key, value] pairs of each element of the map. It returns the [key, value] pairs of all the elements of a map in the order of their insertion. The Map.entries() method does not require any argument to be
    4 min read
  • Iterators & Generators in TypeScript
    Iterators and generators are powerful features in TypeScript (and JavaScript) that allow for the creation and manipulation of sequences of values in a lazy, efficient manner, in this article we shall give a detailed account of what these concepts are all about and how to implement them in TypeScript
    3 min read
  • How to transform a JavaScript iterator into an array ?
    The task is to convert an iterator into an array, this can be performed by iterating each value of the iterator and storing the value in another array. These are the following ways we can add an iterator to an array: Table of Content Using Symbol iterator PropertyUsing Array.from MethodUsing the Spr
    3 min read
  • JavaScript Array values() Method
    JavaScript array.values() is an inbuilt method in JavaScript that is used to return a new array Iterator object that contains the values for each index in the array i.e., it prints all the elements of the array. [GFGTABS] JavaScript // Create an array const fruits = ['Apple', 'Banana
    4 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
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