JavaScript Iterators Example
Greetings readers, in this tutorial, we will understand Iterators in the JavaScript language.
1. Introduction
JavaScript is an object-oriented programming language that allows the client-side scripting to interact with a user and deliver the dynamic pages. Most web browsers including Google Chrome, Mozilla Firefox, Safari, Internet Explorer, Microsoft Edge, Opera, etc. support it. The JavaScript scripting language includes:
- Declaring variables
- Maintaining the retrieving values
- Defining and invoking functions
- Defining classes
- Load and use external modules
- Define event handlers
- And much more ….
1.1 Advantages of JavaScript Language
The pros of using the JavaScript scripting language are:
- JavaScript is easy to learn
- It executes on client’s browser, so eliminates the server-side processing and be executed on any OS
- JavaScript can be used with any type of web page e.g. PHP, ASP.NET, Perl etc
- Web-page performance increases due to client-side execution
- JavaScript code can be minified to decrease the loading time from the server
- Many JavaScript-based application frameworks are available in the market to create Single page web applications e.g. AngularJS, ReactJS etc.
1.2 Disadvantages of JavaScript Language
The cons of using the JavaScript scripting language are:
- No support for networking applications
- Does not have any multi-threading or multi-processing capabilities
- Does not allow the file reading and writing capabilities
1.3 Iterators in JavaScript Language
- Introduced in ES6 to loop over any collection in javascript
- According to ES6, an iterable is a data structure that makes its elements accessible to the public. It is implemented by a method whose key is
Symbol.iterator
- The
Symbol.iterator
method returns an object (i.e. Iterator) with a method callednext()
, which assembles each value in the collection each time it gets called - An iterator is a pointer for traversing the elements of a data structure
Array
,String
,Map
,Set
, andNodeList
are few objects that implement the iterable protocol
2. JavaScript Iterators Example
Here is a systematic guide for implementing this tutorial using the JavaScript language.
2.1 Tools Used
We are using Eclipse Kepler SR2, JDK 8 and Maven. Having said that, we have tested the code against JDK 1.7 and it works well.
2.2 Project Structure
Firstly, let us review the final project structure if you are confused about where you should create the corresponding files or folder later!
2.3 Project Creation
This section will show on how to create a Java-based Maven project with Eclipse. In Eclipse Ide, go to File -> New -> Maven Project
.
In the New Maven Project window, it will ask you to select the project location. By default, ‘Use default workspace location’ will be selected. Just click on the next button to proceed.
Select the ‘Maven Web App’ Archetype from the list of options and click next.
It will ask you to ‘Enter the group and the artifact id for the project’. We will input the details as shown in the below image. The version number will be by default: 0.0.1-SNAPSHOT
.
Click on Finish and the creation of a maven project is completed. If you see, it has downloaded the maven dependencies and a pom.xml
file will be created. It will have the following code:
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.javascript.iterators</groupId> <artifactId>JavascriptIterators</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>war</packaging> </project>
3. Application Building
Let us create an application to understand the basic building blocks of this tutorial.
3.1 Define the HTML
Let us write a simple index page in the JavascriptIterators/src/main/webapp/
folder. Add the following code to it:
index.jsp
<!-- Javascript iterators tutorial --> <div id="title"> <h4 class="text-info">What is a Iterator?</h4> <ul> <li>Introduced in ES6 to loop over any collection in javascript.</li> <li>According to ES6: <ul> <li>An <em>iterable</em> is a data structure that make its elements accessible to the public. It is implemented by a method whose key is <code>Symbol.iterator</code>. <ul> <li>The <code>Symbol.iterator</code> method returns an object (i.e. <mark>Iterator</mark>) with a method called <code>next()</code>, which assembles each value in the collection each time it gets called.</li> </ul> </li> <li>An <em>iterator</em> is a pointer for traversing the elements of a data structure.</li> <li><code>Array</code>, <code>String</code>, <code>Map</code>, <code>Set</code>, and <code>NodeList</code> are few objects that implement the iterable protocol.</li> </ul> </li> </ul> <div> </div> <button id="btn_submit" type="button" class="btn btn-success" onclick="getEmployees();">Click me</button> <div> </div> <ul id="result"></ul>
3.2 Define the JavaScript function
Let us write a simple javascript function that will help developers understand the iterators in the javascript language. Add the following code to it:
JavaScript function
var ul = document.getElementById("result"); // User-defined array. let elist = [ { firstname: 'John', lastname: 'Lark' }, { firstname: 'Natalie', lastname: 'Atlas' }, { firstname: 'Daniel', lastname: 'Brown' }, { firstname: 'Tom', lastname: 'Hunt' }, { firstname: 'Edward', lastname: 'Clark' }, { firstname: 'Jason', lastname: 'Bourne' } ]; function getEmployees() { // Looping through the array elements to display the result. for (let employee of elist) { // Logic to create the dynamic 'li' tags. var li = document.createElement("li"); li.appendChild(document.createTextNode(employee.firstname + " " + employee.lastname)); ul.appendChild(li); } }
3.3 First application
Complete the above steps and save the file. Let us see the sample code snippet.
index.jsp
<!DOCTYPE html> <html lang="en"> <head> <title>Index page</title> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <link rel="stylesheet" href="https://www.webcodegeeks.com/wp-content/litespeed/localres/aHR0cHM6Ly9zdGFja3BhdGguYm9vdHN0cmFwY2RuLmNvbS8=bootstrap/4.1.3/css/bootstrap.min.css"> </head> <body> <div class="container"> <h2 align="center" class="text-danger">Iterators in JavaScript</h2> <hr /> <!-- Javascript iterators tutorial --> <div id="title"> <h4 class="text-info">What is a Iterator?</h4> <ul> <li>Introduced in ES6 to loop over any collection in javascript.</li> <li>According to ES6: <ul> <li>An <em>iterable</em> is a data structure that make its elements accessible to the public. It is implemented by a method whose key is <code>Symbol.iterator</code>. <ul> <li>The <code>Symbol.iterator</code> method returns an object (i.e. <mark>Iterator</mark>) with a method called <code>next()</code>, which assembles each value in the collection each time it gets called.</li> </ul> </li> <li>An <em>iterator</em> is a pointer for traversing the elements of a data structure.</li> <li><code>Array</code>, <code>String</code>, <code>Map</code>, <code>Set</code>, and <code>NodeList</code> are few objects that implement the iterable protocol.</li> </ul> </li> </ul> <div> </div> <button id="btn_submit" type="button" class="btn btn-success" onclick="getEmployees();">Click me</button> <div> </div> <ul id="result"></ul> </div> </div> <script> var ul = document.getElementById("result"); // User-defined array. let elist = [ { firstname: 'John', lastname: 'Lark' }, { firstname: 'Natalie', lastname: 'Atlas' }, { firstname: 'Daniel', lastname: 'Brown' }, { firstname: 'Tom', lastname: 'Hunt' }, { firstname: 'Edward', lastname: 'Clark' }, { firstname: 'Jason', lastname: 'Bourne' } ]; function getEmployees() { // Looping through the array elements to display the result. for (let employee of elist) { // Logic to create the dynamic 'li' tags. var li = document.createElement("li"); li.appendChild(document.createTextNode(employee.firstname + " " + employee.lastname)); ul.appendChild(li); } } </script> </body> </html>
4. Run the Application
As we are ready for all the changes, let us compile the project and deploy the application on the Tomcat7 server. To deploy the application on Tomat7, right-click on the project and navigate to Run as -> Run on Server
.
Tomcat will deploy the application in its web-apps folder and shall start its execution to deploy the project so that we can go ahead and test it in the browser.
5. Project Demo
Open your favorite browser and hit the following URL to display the application’s index page as shown in Fig. 7.
http://localhost:8082/JavascriptIterators/
Server name (localhost) and port (8082) may vary as per your Tomcat configuration.
Users can click the button to display the employee names as shown in fig.8.
That is all for this tutorial and I hope the article served you whatever you were looking for. Happy learning and do not forget to share.
6. Conclusion
In this section, developers learned how to create a simple application with the JavaScript language. Developers can download the sample application as an Eclipse project in the Downloads section.
7. Download the Eclipse Project
This was a beginner’s tutorial to understand the iterators in the javascript language.
You can download the full source code of this example here: JavascriptIterators