JavaScript foreach method | Loop and break Example

JavaScript foreach method is used in Array to Iterate through its items. This means its provided function once for each element of the array.

Note: the function is not executed for array elements without values.


Parameter Values

  • array:- A array on which the .forEach() function was called. (Optional)
  • index:- Array index of the current element. (Optional)
  • element:- The value of the current element (Required)
  • thisValue:- Used to tell the function to use this value when executing the argument function.

Return value

This function returns always undefined and may not change the original array provided as it depends upon the functionality of the argument function.

Examples of JavaScript foreach method

Let’s see the examples with many scenarios.

Simple example

How to sum of all the values in the array using foreach method in js.


JavaScript foreach method

Update values of Array

let’s Update the value with 10 times the original value:


JS foreach method Loop and break Example

JavaScript foreach push to array

Example of forEach loop to get element from array & push into new array (updated value).


JavaScript foreach push to array

JavaScript foreach break

There’s no built-in ability to break in forEach. To interrupt execution you would have to throw an exception of some sort. eg.

Q: How to use JavaScript foreach arrow function?

Answer: You can use it like:

But you’d better use arrow function in this way,and there is no need to define function callback

Do comment if you know about the another example. Also do comment if you have any doubts and suggestions.

Note: The All JS Examples codes are tested on the Safari browser (Version 12.0.2) and Chrome.
OS: macOS 10.14 Mojave
Code: HTML 5 Version

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.