Skip to content

JavaScript foreach method | Loop and break Example

  • by

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.

Syntax

array.forEach(function(currentValue, index, arr), thisValue)

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 for each method in JS.

<!DOCTYPE html>
<html>
    <head>
        <title> Example</title>
        <script type="text/javascript">
        var sum = 0;
		var numbers = [5, 1, 2, 4];

		numbers.forEach(myFunction);

		function myFunction(item) {
  			sum += item;  			
		}
		// show output in alert
        	alert(sum)
      
        </script>
    </head>
    
</html>

Output:

JavaScript foreach method

Update values of Array

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

<!DOCTYPE html>
<html>
    <head>
        <title> Example</title>
        <script type="text/javascript">
        var sum = 0;
		var numbers = [5, 1, 2, 4];

		numbers.forEach(myFunction);

		function myFunction(item, index, arr) {
  			arr[index] = item * 10;
		}
		// show output in alert
        	alert(numbers)
      
        </script>
    </head>
    
</html>

Output:

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).

<!DOCTYPE html>
<html>
    <head>
        <title> Example</title>
        <script type="text/javascript">
		var numbers = [5, 1, 2, 4];
		const copy = [];

		numbers.forEach(function(item){
  			copy.push(item*item);
		});
		// show output in alert
        	alert(copy)
      
        </script>
    </head>
    
</html>

Output:

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.

var BreakException = {};

try {
  [1, 2, 3].forEach(function(el) {
    console.log(el);
    if (el === 2) throw BreakException;
  });
} catch (e) {
  if (e !== BreakException) throw e;
}

Q: How to use JavaScript foreach arrow function?

Answer: You can use it like:

ary.forEach(i=>callback);

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

let ary = [1,2,3,4,5];

ary.forEach(i=>{
  console.log(i);
});

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

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading