Skip to content
Home » for-Each In JavaScript With Example

for-Each In JavaScript With Example

Introduction and Usage

for-Each In JavaScript, the forEach() function iterate the elements of an array once one by one in order. Using for-Each() function or method we also iterate object elements.

forEach In JavaScript With Example
forEach in JS

Syntax

ArgumentDescription
currentValueThe value of the current element. (Required)
indexThe array index of the current element. (Optional)
arrThe array object the current element belongs to. (Optional)

Example of forEach in JavaScript

Output:

a
b
c

  • In the above example, we create an array.
  • Then we iterate that array element using forEach() method.
  • And method stores the output of an iterated array on that parameter.

Iterate Object Using for-Each in JavaScript

Output:

“foo: bar” “baz: 42”

  • In the above example, we create an object and assign it to a CONST type.
  • Object.entries(obj) returns an array or an object’s own enumerable string.
  • Then we use forEach() with Object.entries(obj).
  • In this process, the first object converts to an array and then iterates by the forEach() function.

See the Pen Foreach and Map Example JS by Bikash Panda (@phpcodertech) on CodePen.

Here is the complete explanation with examples.

To know more Object.entries() – JavaScript | MDN (mozilla.org)

Also, Read

Happy Coding..!

Was this article helpful?
YesNo

Leave a Reply

Your email address will not be published. Required fields are marked *