×

Index

JavaScript Tutorial

JavaScript Examples

CSS Tutorial

CSS Examples

JavaScript - Iterating an array with index and element

By IncludeHelp Last updated : January 21, 2024

Problem statement

Given a JavaScript Array, you have to iterate the given with index and element.

Iterating an array with index and element

To iterate an array with index and element, you can use the for ... of loop with Array.entries() method. The Array.entries() method creates an Iterator of this array to iterate over the key/value pairs.

JavaScript code to iterate an array with index and element

The following code iterates an array (arr), and extracts and prints the index and elements.

// creating an array
const arr = ["New Delhi", "New York", "California", "London"];

// Iterating an array with index and element
for (const [key, value] of arr.entries()) {
  console.log(key, value);
}

Output

The output of the above code is:

0 'New Delhi'
1 'New York'
2 'California'
3 'London'
Note

Never miss to write JavaScript code inside the <script>...</script> tag.

Also Learn: Where to place JavaScript Code?

To understand the above example, you should have the basic knowledge of the following JavaScript topics:

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.