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.
Syntax
1 |
array.forEach(function(currentValue, index, arr), thisValue) |
Argument | Description |
---|---|
currentValue | The value of the current element. (Required) |
index | The array index of the current element. (Optional) |
arr | The array object the current element belongs to. (Optional) |
Example of forEach in JavaScript
1 2 3 4 |
var a = ["a", "b", "c"]; a.forEach(function(entry) { console.log(entry); }); |
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
1 2 3 4 5 6 |
/* 1st Example */ const obj = { foo: 'bar', baz: 42 }; Object.entries(obj).forEach(([key, value]) => console.log(`${key}: ${value}`)); |
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
- How to Get Current Date and Time In JavaScript
- Set PHP Error Reporting Into The PHP File
- How to Convert JSON to Array PHP
- Remove Duplicates From an Array in JavaScript Without Using For Loop
Happy Coding..!
3 Replies to “for-Each In JavaScript With Example”