The Wayback Machine - https://web.archive.org/web/20240920014713/https://www.geeksforgeeks.org/javascript-iterator/
Open In App

JavaScript Iterator

Last Updated : 27 Dec, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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


Similar Reads

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 property. In place of @@iterator, we can use Symbol.
2 min read
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 function i.e, values() function by default. JavaS
1 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 which is not an array but does possess a group of
2 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 @@iterator property of String. In place of @@iterator,
2 min read
How to Create Custom Iterator that Skips Empty Value in JavaScript ?
Iterators are important concepts in the world of programming. They allow developers to traverse and manipulate collections of data more efficiently and flexibly. JavaScript, being a high-level programming language, also supports iterators. You can even create a custom iterator that skips the empty values using the below methods: Table of Content Us
3 min read
Difference Between Symbol.iterator and Symbol.asyncIterator in JavaScript
JavaScript offers powerful mechanisms for handling iteration through objects, especially with the introduction of symbols like Symbol.iterator and Symbol.asyncIterator. These symbols play important roles in defining how objects are iterated over, whether synchronously or asynchronously. In this article, we will explore the differences between Symbo
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 Spread OperatorUsing a for...of LoopUsing map()Using
3 min read
How to get index at which the value should be inserted into sorted array based on iterator function in JavaScript ?
In this article, we will learn how to get an index at which the value should be inserted into a sorted array based on the iterator function in JavaScript. Here we use the sorting function to sort the array and we would print the array and the position of the new element in the DOM. Approach: Create an empty array.Now make a sorting function by taki
4 min read
Lodash _.prototype[Symbol.iterator]() Method
Lodash _.prototype[Symbol.iterator]() method of Sequence in lodash is used to permit the wrapper to be iterable. Syntax:_.prototype[Symbol.iterator]();Parameters: This method doesn't accept any parameter. Return Value: This method returns the lodash wrapper object. Example 1: In this example, we are using the lodash _.prototype[Symbol.iterator]() m
1 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 iterator: Iterator&lt;T&gt; = array[Symbol.iterator]();Pa
3 min read
JavaScript Course Understanding Code Structure in JavaScript
Inserting JavaScript into a webpage is much like inserting any other HTML content. The tags used to add JavaScript in HTML are &lt;script&gt; and &lt;/script&gt;. The code surrounded by the &lt;script&gt; and &lt;/script&gt; tags is called a script blog. The 'type' attribute was the most important attribute of &lt;script&gt; tag. However, it is no
4 min read
Introduction to JavaScript Course - Learn how to build a task tracker using JavaScript
This is an introductory course about JavaScript that will help you learn about the basics of javascript, to begin with, the dynamic part of web development. You will learn the basics like understanding code structures, loops, objects, etc. What this course is about? In this course we will teach you about the basics of the scripting language i.e) Ja
4 min read
JavaScript Course Loops in JavaScript
Looping in programming languages is a feature that facilitates the execution of a set of instructions/functions repeatedly while some condition evaluates to true. For example, suppose we want to print “Hello World” 10 times. Example: In this example we will print the same things, again and again, to understand the work of Loops. &lt;script&gt; cons
4 min read
JavaScript Course Logical Operators in JavaScript
logical operator is mostly used to make decisions based on conditions specified for the statements. It can also be used to manipulate a boolean or set termination conditions for loops. There are three types of logical operators in Javascript: !(NOT): Converts operator to boolean and returns flipped value &amp;&amp;:(AND) Evaluates operands and retu
3 min read
JavaScript Course What is JavaScript ?
JavaScript is a very famous programming language that was originally started in the year of 1995 with the motive of making web pages alive. It is also an essential part of the web developer skillset. In simple terms, if you want to learn web development then learn HTML & CSS before starting JavaScript. HTML: HTML is used to create the structure of
3 min read
JavaScript Course Operators in JavaScript
An operator is capable of manipulating a certain value or operand. Operators are used to performing specific mathematical and logical computations on operands. In other words, we can say that an operator operates the operands. In JavaScript, operators are used for comparing values, performing arithmetic operations, etc. There are various operators
7 min read
JavaScript Course Functions in JavaScript
Javascript functions are code blocks that are mainly used to perform a particular function. We can execute a function as many times as we want by calling it(invoking it). Function Structure: To create a function, we use function() declaration. // Anonymous function function(){ // function...body } // function with a name function displayMessage(){
4 min read
JavaScript Course Conditional Operator in JavaScript
JavaScript Conditional Operators allow us to perform different types of actions according to different conditions. We make use of the 'if' statement. if(expression){ do this; } The above argument named 'expression' is basically a condition that we pass into the 'if' and if it returns 'true' then the code block inside it will be executed otherwise n
3 min read
JavaScript Course Objects in JavaScript
We have learned about different Data Types that javascript provides us, most of them primitive in nature. Objects are not primitive in nature and are a bit complex to understand. Everything in javascript is basically an object, and that is the reason why it becomes very important to have a good understanding of what they are. Objects are used to st
4 min read
JavaScript vs Python : Can Python Overtop JavaScript by 2020?
This is the Clash of the Titans!! And no...I am not talking about the Hollywood movie (don’t bother watching it...it's horrible!). I am talking about JavaScript and Python, two of the most popular programming languages in existence today. JavaScript is currently the most commonly used programming language (and has been for quite some time!) but now
5 min read
How to compare two JavaScript array objects using jQuery/JavaScript ?
In this article, we are given two JavaScript array/array objects and the task is to compare the equality of both array objects. These are the methods to compare two JavaScript array objects: Using jQuery not() methodUse the sort() functionUse JSON.stringify() functionUsing every() and indexOf()Using Lodash _.isEqual() MethodApproach 1: Using jQuery
3 min read
How can JavaScript codes be hidden from old browsers that do not support JavaScript ?
Nowadays all modern browsers support JavaScript, however, older browsers did not support JavaScript. In this article, we will learn how we can hide JavaScript code from running in older browsers. Approach: After opening the &lt;script&gt; tag, we will use a one-line HTML style comment without any closing character ( &lt;!-- ). We will then write th
2 min read
How are the JavaScript window and JavaScript document different from one another?
What is a JavaScript window? The window is at a root/top level at the JavaScript object hierarchy. It is a global/root object in JavaScript and it is the root object of the Document object model(DOM); What is a JavaScript document? A document is an object inside the window object and we use a document object for manipulation inside the document. Th
3 min read
Explore the concept of JavaScript Function Scope and different types of JavaScript Functions
JavaScript is based on functional programming. Therefore, functions are fundamental building blocks of JavaScript. So the function is called first-class citizens in JavaScript. Syntax: Define a functionfunction functionName(parameters) { // SET OF STATEMENTS } Call a functionfunctionName(arguments); The function execution stops when all the stateme
10 min read
Which href value should we use for JavaScript links, "#" or "javascript:void(0)" ?
In this article, we will know which "href" should be used for JavaScript when we can use "#" or "javascript:void(0)". Let us understand it. Using the '#' value: The # is a fragment identifier used to refer to a specific section of the same document. When a user clicks a link with a # href, the browser will scroll to that section of the page specifi
3 min read
How to include a JavaScript file in another JavaScript file ?
In native JavaScript, before ES6 Modules 2015 was introduced had no import, include, or require functionalities. Before that, we can load a JavaScript file into another JavaScript file using a script tag inside the DOM that script will be downloaded and executed immediately. Now after the invention of ES6 modules, there are so many different approa
3 min read
JavaScript Program to find Length of Linked List using JavaScript
Given a linked list, the task is to determine its length using various methods. The linked list is a fundamental data structure consisting of nodes connected in a chain, offering efficient data organization. Different approaches, including Iterative and Recursive Methods, enable us to compute the length of a linked list easily. Use the below approa
3 min read
JavaScript Cheat Sheet - A Basic Guide to JavaScript
JavaScript is a lightweight, open, and cross-platform programming language. It is omnipresent in modern development and is used by programmers across the world to create dynamic and interactive web content like applications and browsers. It is one of the core technologies of the World Wide Web, alongside HTML and CSS, and the powerhouse behind the
15+ min read
JavaScript Course Variables in JavaScript
Variables in JavaScript are containers that hold reusable data. It is the basic unit of storage in a program. The value stored in a variable can be changed during program execution. A variable is only a name given to a memory location, all the operations done on the variable effects that memory location. In JavaScript, all the variables must be dec
4 min read
JavaScript Complete Guide - A to Z JavaScript Concepts
What is JavaScript ? JavaScript is a lightweight, cross-platform, single-threaded, and interpreted compiled programming language. It is also known as the scripting language for webpages. What is JavaScript Complete Guide ? JavaScript Complete Guide is a list of A to Z JavaScript concepts from beginner to advanced level. Table of Contents Introducti
8 min read