Cara menggunakan foreach javascript not working

What's the usual thing you do with an array? Iterate through its items! This is where

javascript

const colors = ['blue', 'green', 'white'];

function iterate(item) {

console.log(item);

}

colors.forEach(iterate);

// logs "blue"

// logs "green"

// logs "white"

4 array method can be helpful.

This post describes how to use

javascript

const colors = ['blue', 'green', 'white'];

function iterate(item) {

console.log(item);

}

colors.forEach(iterate);

// logs "blue"

// logs "green"

// logs "white"

4 array method to iterate items of an array in JavaScript. Plus, you will read about

javascript

const colors = ['blue', 'green', 'white'];

function iterate(item) {

console.log(item);

}

colors.forEach(iterate);

// logs "blue"

// logs "green"

// logs "white"

4 best practices like correct handling of

javascript

const colors = ['blue', 'green', 'white'];

function iterate(item) {

console.log(item);

}

colors.forEach(iterate);

// logs "blue"

// logs "green"

// logs "white"

7 and how to iterate array-like objects.

1. Basic forEach example

javascript

const colors = ['blue', 'green', 'white'];

function iterate(item) {

console.log(item);

}

colors.forEach(iterate);

// logs "blue"

// logs "green"

// logs "white"

8 method iterates over the array items, in ascending order, without mutating the array.

The first argument of

javascript

const colors = ['blue', 'green', 'white'];

function iterate(item) {

console.log(item);

}

colors.forEach(iterate);

// logs "blue"

// logs "green"

// logs "white"

4 is the callback function called for every item in the array. The second argument (optional) is the value of

javascript

const colors = ['blue', 'green', 'white'];

function iterate(item) {

console.log(item);

}

colors.forEach(iterate);

// logs "blue"

// logs "green"

// logs "white"

7 set in the callback.

javascript

array.forEach(callback [, thisArgument])

Let's see how

javascript

const colors = ['blue', 'green', 'white'];

function iterate(item) {

console.log(item);

}

colors.forEach(iterate);

// logs "blue"

// logs "green"

// logs "white"

4 works in practice.

In the following example,

javascript

array.forEach(callback(item [, index [, array]]))

2 array has 3 items. Let's use

javascript

const colors = ['blue', 'green', 'white'];

function iterate(item) {

console.log(item);

}

colors.forEach(iterate);

// logs "blue"

// logs "green"

// logs "white"

4 to log to console every color:

javascript

const colors = ['blue', 'green', 'white'];

function iterate(item) {

console.log(item);

}

colors.forEach(iterate);

// logs "blue"

// logs "green"

// logs "white"

javascript

array.forEach(callback(item [, index [, array]]))

4 a the callback function.

javascript

array.forEach(callback(item [, index [, array]]))

5 executes

javascript

array.forEach(callback(item [, index [, array]]))

4 function for every item in

javascript

array.forEach(callback(item [, index [, array]]))

2, setting the iterated item as the first argument.

This way, 3 invocation of

javascript

array.forEach(callback(item [, index [, array]]))

8 function are perfomed:

  • javascript

    array.forEach(callback(item [, index [, array]]))

    9
  • javascript

    const colors = ['blue', 'green', 'white'];

    function iterate(item, index) {

    console.log(`${item} has index ${index}`);

    }

    colors.forEach(iterate);

    // logs "blue has index 0"

    // logs "green has index 1"

    // logs "white has index 2"

    0
  • javascript

    const colors = ['blue', 'green', 'white'];

    function iterate(item, index) {

    console.log(`${item} has index ${index}`);

    }

    colors.forEach(iterate);

    // logs "blue has index 0"

    // logs "green has index 1"

    // logs "white has index 2"

    1

That's how, in a few words,

javascript

const colors = ['blue', 'green', 'white'];

function iterate(item) {

console.log(item);

}

colors.forEach(iterate);

// logs "blue"

// logs "green"

// logs "white"

4 method works.

2. Index of the iterated element

javascript

const colors = ['blue', 'green', 'white'];

function iterate(item, index) {

console.log(`${item} has index ${index}`);

}

colors.forEach(iterate);

// logs "blue has index 0"

// logs "green has index 1"

// logs "white has index 2"

3 executes the

javascript

const colors = ['blue', 'green', 'white'];

function iterate(item, index) {

console.log(`${item} has index ${index}`);

}

colors.forEach(iterate);

// logs "blue has index 0"

// logs "green has index 1"

// logs "white has index 2"

4 function with 3 arguments: the current iterated item, the index of the iterated item and the array instance itself.

javascript

array.forEach(callback(item [, index [, array]]))

Let's access the index of each item in the colors array:

javascript

const colors = ['blue', 'green', 'white'];

function iterate(item, index) {

console.log(`${item} has index ${index}`);

}

colors.forEach(iterate);

// logs "blue has index 0"

// logs "green has index 1"

// logs "white has index 2"

javascript

array.forEach(callback(item [, index [, array]]))

8 function has access to the current iterated item and the index. The callback is executed 3 times:

  • javascript

    const colors = ['blue', 'green', 'white'];

    function iterate(item, index) {

    console.log(`${item} has index ${index}`);

    }

    colors.forEach(iterate);

    // logs "blue has index 0"

    // logs "green has index 1"

    // logs "white has index 2"

    6
  • javascript

    const colors = ['blue', 'green', 'white'];

    function iterate(item, index) {

    console.log(`${item} has index ${index}`);

    }

    colors.forEach(iterate);

    // logs "blue has index 0"

    // logs "green has index 1"

    // logs "white has index 2"

    7
  • javascript

    const colors = ['blue', 'green', 'white'];

    function iterate(item, index) {

    console.log(`${item} has index ${index}`);

    }

    colors.forEach(iterate);

    // logs "blue has index 0"

    // logs "green has index 1"

    // logs "white has index 2"

    8

3. Access the array inside the callback

To access the array itself during the iteration, you can use the 3rd parameter inside the callback function.

Let's log the message

javascript

const colors = ['blue', 'green', 'white'];

function iterate(item, index) {

console.log(`${item} has index ${index}`);

}

colors.forEach(iterate);

// logs "blue has index 0"

// logs "green has index 1"

// logs "white has index 2"

9 when JavaScript executes the last iteration on the array items.

javascript

const colors = ['blue', 'green', 'white'];

function iterate(item, index, array) {

console.log(item);

if (index === array.length - 1) {

console.log('The last iteration!');

}

}

colors.forEach(iterate);

// logs "blue"

// logs "green"

// logs "white"

// logs "The last iteration!"

The 3rd parameter

javascript

const colors = ['blue', 'green', 'white'];

function iterate(item, index, array) {

console.log(item);

if (index === array.length - 1) {

console.log('The last iteration!');

}

}

colors.forEach(iterate);

// logs "blue"

// logs "green"

// logs "white"

// logs "The last iteration!"

0 inside the callback function is the array on which

javascript

const colors = ['blue', 'green', 'white'];

function iterate(item) {

console.log(item);

}

colors.forEach(iterate);

// logs "blue"

// logs "green"

// logs "white"

4 method was called on.

4. this inside the callback

Let's run the following example in a browser, and pay attention to the value of

javascript

const colors = ['blue', 'green', 'white'];

function iterate(item) {

console.log(item);

}

colors.forEach(iterate);

// logs "blue"

// logs "green"

// logs "white"

7:

javascript

const letters = ['a', 'b', 'c'];

function iterate(letter) {

console.log(this === window); // true

}

letters.forEach(iterate); // logs 3 times "true"

javascript

const colors = ['blue', 'green', 'white'];

function iterate(item) {

console.log(item);

}

colors.forEach(iterate);

// logs "blue"

// logs "green"

// logs "white"

7 inside

javascript

array.forEach(callback(item [, index [, array]]))

8 equals to

javascript

const colors = ['blue', 'green', 'white'];

function iterate(item, index, array) {

console.log(item);

if (index === array.length - 1) {

console.log('The last iteration!');

}

}

colors.forEach(iterate);

// logs "blue"

// logs "green"

// logs "white"

// logs "The last iteration!"

5, which is the global object in the browser environment. Follow to get more information.

In some situations, you might need to set

javascript

const colors = ['blue', 'green', 'white'];

function iterate(item) {

console.log(item);

}

colors.forEach(iterate);

// logs "blue"

// logs "green"

// logs "white"

7 to an object of interest. Then indicate this object as the second argument when calling

javascript

const colors = ['blue', 'green', 'white'];

function iterate(item) {

console.log(item);

}

colors.forEach(iterate);

// logs "blue"

// logs "green"

// logs "white"

4:

javascript

array.forEach(callback, thisArgument)

Let's implement a

javascript

const colors = ['blue', 'green', 'white'];

function iterate(item, index, array) {

console.log(item);

if (index === array.length - 1) {

console.log('The last iteration!');

}

}

colors.forEach(iterate);

// logs "blue"

// logs "green"

// logs "white"

// logs "The last iteration!"

8 class, which always holds an unique list of items:

javascript

class Unique {

constructor(items) {

this.items = items;

}

append(newItems) {

newItems.forEach(function(newItem) {

if (!this.items.includes(newItem)) {

this.items.push(newItem);

}

}, this);

}

}

const uniqueColors = new Unique(['blue']);

console.log(uniqueColors.items); // => ['blue']

uniqueColors.append(['red', 'blue']);

console.log(uniqueColors.items); // => ['blue', 'red']

javascript

const colors = ['blue', 'green', 'white'];

function iterate(item, index, array) {

console.log(item);

if (index === array.length - 1) {

console.log('The last iteration!');

}

}

colors.forEach(iterate);

// logs "blue"

// logs "green"

// logs "white"

// logs "The last iteration!"

9 is called with the second argument pointing to

javascript

const colors = ['blue', 'green', 'white'];

function iterate(item) {

console.log(item);

}

colors.forEach(iterate);

// logs "blue"

// logs "green"

// logs "white"

7, i.e. the instance of

javascript

const colors = ['blue', 'green', 'white'];

function iterate(item, index, array) {

console.log(item);

if (index === array.length - 1) {

console.log('The last iteration!');

}

}

colors.forEach(iterate);

// logs "blue"

// logs "green"

// logs "white"

// logs "The last iteration!"

8 class.

Inside the callback of

javascript

const colors = ['blue', 'green', 'white'];

function iterate(item) {

console.log(item);

}

colors.forEach(iterate);

// logs "blue"

// logs "green"

// logs "white"

4,

javascript

const colors = ['blue', 'green', 'white'];

function iterate(item) {

console.log(item);

}

colors.forEach(iterate);

// logs "blue"

// logs "green"

// logs "white"

7 points also to an instance of

javascript

const colors = ['blue', 'green', 'white'];

function iterate(item, index, array) {

console.log(item);

if (index === array.length - 1) {

console.log('The last iteration!');

}

}

colors.forEach(iterate);

// logs "blue"

// logs "green"

// logs "white"

// logs "The last iteration!"

8. Now it's safe to access

javascript

const letters = ['a', 'b', 'c'];

function iterate(letter) {

console.log(this === window); // true

}

letters.forEach(iterate); // logs 3 times "true"

5.

Note that for the above example using an arrow function as the callback of

javascript

const colors = ['blue', 'green', 'white'];

function iterate(item) {

console.log(item);

}

colors.forEach(iterate);

// logs "blue"

// logs "green"

// logs "white"

4 would be better. The the value of

javascript

const colors = ['blue', 'green', 'white'];

function iterate(item) {

console.log(item);

}

colors.forEach(iterate);

// logs "blue"

// logs "green"

// logs "white"

7 from the lexical scope, so there's no need to use the second argument on

javascript

const colors = ['blue', 'green', 'white'];

function iterate(item) {

console.log(item);

}

colors.forEach(iterate);

// logs "blue"

// logs "green"

// logs "white"

4.

5. forEach skips empty slots

javascript

const colors = ['blue', 'green', 'white'];

function iterate(item) {

console.log(item);

}

colors.forEach(iterate);

// logs "blue"

// logs "green"

// logs "white"

4 skips the empty slots of the array (named ).

javascript

const sparseArray = [1, , 3];

sparseArray.length; // => 3

sparseArray.forEach(function(item) {

console.log(item);

}); // logs 1, 3

javascript

array.forEach(callback, thisArgument)

0 contains

javascript

array.forEach(callback, thisArgument)

1, an empty slot, and

javascript

array.forEach(callback, thisArgument)

2.

javascript

const colors = ['blue', 'green', 'white'];

function iterate(item) {

console.log(item);

}

colors.forEach(iterate);

// logs "blue"

// logs "green"

// logs "white"

4 iterates over

javascript

array.forEach(callback, thisArgument)

1 and

javascript

array.forEach(callback, thisArgument)

2, but skips the empty slot.

6. Iterate array-like objects using forEach

javascript

const colors = ['blue', 'green', 'white'];

function iterate(item) {

console.log(item);

}

colors.forEach(iterate);

// logs "blue"

// logs "green"

// logs "white"

4 can iterate over array-like objects:

javascript

const arrayLikeColors = {

"0": "blue",

"1": "green",

"2": "white",

"length": 3

};

function iterate(item) {

console.log(item);

}

Array.prototype.forEach.call(arrayLikeColors, iterate);

// logs "blue"

// logs "green"

// logs "white"

javascript

array.forEach(callback, thisArgument)

7 is an array-like object. In order to iterate over its items, you have to call indirectly

javascript

const colors = ['blue', 'green', 'white'];

function iterate(item) {

console.log(item);

}

colors.forEach(iterate);

// logs "blue"

// logs "green"

// logs "white"

4 using the

javascript

array.forEach(callback, thisArgument)

9. The

javascript

const colors = ['blue', 'green', 'white'];

function iterate(item) {

console.log(item);

}

colors.forEach(iterate);

// logs "blue"

// logs "green"

// logs "white"

4 method is taken from

javascript

class Unique {

constructor(items) {

this.items = items;

}

append(newItems) {

newItems.forEach(function(newItem) {

if (!this.items.includes(newItem)) {

this.items.push(newItem);

}

}, this);

}

}

const uniqueColors = new Unique(['blue']);

console.log(uniqueColors.items); // => ['blue']

uniqueColors.append(['red', 'blue']);

console.log(uniqueColors.items); // => ['blue', 'red']

1.

Alternatively, you can transform the array-like object into an array using

javascript

class Unique {

constructor(items) {

this.items = items;

}

append(newItems) {

newItems.forEach(function(newItem) {

if (!this.items.includes(newItem)) {

this.items.push(newItem);

}

}, this);

}

}

const uniqueColors = new Unique(['blue']);

console.log(uniqueColors.items); // => ['blue']

uniqueColors.append(['red', 'blue']);

console.log(uniqueColors.items); // => ['blue', 'red']

2, then iterate:

javascript

const colors = ['blue', 'green', 'white'];

function iterate(item) {

console.log(item);

}

colors.forEach(iterate);

// logs "blue"

// logs "green"

// logs "white"

0

7. When to use forEach()

javascript

const colors = ['blue', 'green', 'white'];

function iterate(item) {

console.log(item);

}

colors.forEach(iterate);

// logs "blue"

// logs "green"

// logs "white"

4 is best used to iterate array items, without breaking, and having simultaneously some side-effect.

Side-effects examples are a mutation of an outer scope variable, I/O operations (HTTP requests), DOM manipulations, and alike.

For example, let's select all input elements from the DOM and use

javascript

const colors = ['blue', 'green', 'white'];

function iterate(item) {

console.log(item);

}

colors.forEach(iterate);

// logs "blue"

// logs "green"

// logs "white"

4 to clear them:

javascript

const colors = ['blue', 'green', 'white'];

function iterate(item) {

console.log(item);

}

colors.forEach(iterate);

// logs "blue"

// logs "green"

// logs "white"

1

The side effect in the callback function is clearing the value of the input field.

Keep in mind that you cannot normally break the iteration of

javascript

const colors = ['blue', 'green', 'white'];

function iterate(item) {

console.log(item);

}

colors.forEach(iterate);

// logs "blue"

// logs "green"

// logs "white"

4 (other than a tricky way to throw an error to stop the iteration, which is a cheap hack). The method will always iterate over all the items.

If your case requires an early break from the cycle, a better option is the classic for or for..of.

When the array iteration computes a result, without side-effects, a better alternative is to select an array method like:

  • array.map()
  • array.reduce()
  • array.every()
  • array.some()

For example, let's determine whether all numbers of an array are even.

The first solution involves

javascript

const colors = ['blue', 'green', 'white'];

function iterate(item) {

console.log(item);

}

colors.forEach(iterate);

// logs "blue"

// logs "green"

// logs "white"

4 method:

javascript

const colors = ['blue', 'green', 'white'];

function iterate(item) {

console.log(item);

}

colors.forEach(iterate);

// logs "blue"

// logs "green"

// logs "white"

2

The code determines correctly if all numbers are even. The problem is the impossibility to break after finding the first odd number

javascript

array.forEach(callback, thisArgument)

2.

For this situation, a better alternative is

javascript

class Unique {

constructor(items) {

this.items = items;

}

append(newItems) {

newItems.forEach(function(newItem) {

if (!this.items.includes(newItem)) {

this.items.push(newItem);

}

}, this);

}

}

const uniqueColors = new Unique(['blue']);

console.log(uniqueColors.items); // => ['blue']

uniqueColors.append(['red', 'blue']);

console.log(uniqueColors.items); // => ['blue', 'red']

8 method:

javascript

const colors = ['blue', 'green', 'white'];

function iterate(item) {

console.log(item);

}

colors.forEach(iterate);

// logs "blue"

// logs "green"

// logs "white"

3

javascript

class Unique {

constructor(items) {

this.items = items;

}

append(newItems) {

newItems.forEach(function(newItem) {

if (!this.items.includes(newItem)) {

this.items.push(newItem);

}

}, this);

}

}

const uniqueColors = new Unique(['blue']);

console.log(uniqueColors.items); // => ['blue']

uniqueColors.append(['red', 'blue']);

console.log(uniqueColors.items); // => ['blue', 'red']

8 doesn't only make the code shorter. It is also optimal, because

javascript

const sparseArray = [1, , 3];

sparseArray.length; // => 3

sparseArray.forEach(function(item) {

console.log(item);

}); // logs 1, 3

0 method breaks iterating after finding the first odd number.

8. Conclusion

javascript

const colors = ['blue', 'green', 'white'];

function iterate(item, index) {

console.log(`${item} has index ${index}`);

}

colors.forEach(iterate);

// logs "blue has index 0"

// logs "green has index 1"

// logs "white has index 2"

3 method is an efficient way to iterate over all array items. Its first argument is the

javascript

const colors = ['blue', 'green', 'white'];

function iterate(item, index) {

console.log(`${item} has index ${index}`);

}

colors.forEach(iterate);

// logs "blue has index 0"

// logs "green has index 1"

// logs "white has index 2"

4 function, which is invoked for every item in the array with 3 arguments: item, index, and the array itself.

javascript

const colors = ['blue', 'green', 'white'];

function iterate(item) {

console.log(item);

}

colors.forEach(iterate);

// logs "blue"

// logs "green"

// logs "white"

4 is useful to iterate over all array items, without breaking, involving simultaneously some side-effects. Otherwise, consider an alternative array method.

Do you know good uses cases of

javascript

const colors = ['blue', 'green', 'white'];

function iterate(item) {

console.log(item);

}

colors.forEach(iterate);

// logs "blue"

// logs "green"

// logs "white"

4? Write them in a comment below.

Like the post? Please share!

Suggest Improvement

Quality posts into your inbox

I regularly publish posts containing:

  • Important JavaScript concepts explained in simple words
  • Overview of new JavaScript features
  • How to use TypeScript and typing
  • Software design and good coding practices

Subscribe to my newsletter to get them right into your inbox.

Subscribe

Join 6861 other subscribers.

Cara menggunakan foreach javascript not working

Cara menggunakan foreach javascript not working

About Dmitri Pavlutin

Tech writer and coach. My daily routine consists of (but not limited to) drinking coffee, coding, writing, coaching, overcoming boredom 😉.

Now working as a full-time open source developer on Readapt project - aiming to make the web accessible for everyone.