Golang Tutorials - Learn Go Programming with Easy Step-by-Step Guides

Explore comprehensive Golang tutorials for beginners and advanced programmers. Learn Go programming with easy-to-follow, step-by-step guides, examples, and practical tips to master Go language quickly.

Js Array Iteration in JavaScript

Js Array Iteration in JavaScript

? JavaScript Array Iteration


Common Ways to Iterate Over Arrays in JavaScript

1. for Loop (Classic)

const arr = [10, 20, 30];for (let i = 0; i < arr.length; i++) {  console.log(arr[i]);}

2. for...of Loop (ES6+)

for (const value of arr) {  console.log(value);}
  • Cleaner syntax for iterating over iterable objects (like arrays).


3. forEach() Method

arr.forEach(function(value, index) {  console.log(index, value);});// Using arrow functionarr.forEach((value, index) => {  console.log(index, value);});
  • Takes a callback executed once per element.

  • Cannot be broken early (no break).


4. map() Method

const doubled = arr.map(value => value * 2);console.log(doubled);  // [20, 40, 60]
  • Returns a new array by applying a function to each element.


5. for...in Loop (Not Recommended for Arrays)

for (const index in arr) {  console.log(index, arr[index]);}
  • Iterates over keys (indexes), but also over inherited enumerable properties.

  • Generally, avoid for arrays; prefer for, for...of, or forEach.


Summary Table

MethodDescriptionBreakable?Returns New Array?
for loopClassic index-based loopYesNo
for...ofLoop over valuesYes (with break)No
forEach()Callback per elementNoNo
map()Transform each elementNoYes
for...inLoop over keys (not recommended for arrays)YesNo

Example: Print Each Element

const fruits = ["apple", "banana", "cherry"];// Using forEachfruits.forEach((fruit, i) => {  console.log(i + ": " + fruit);});

Need examples on filtering, reducing, or finding elements in arrays?

Disclaimer for AI-Generated Content:
The content provided in these tutorials is generated using artificial intelligence and is intended for educational purposes only.
html
docker
php
kubernetes
golang
mysql
postgresql
mariaDB
sql