Exploring the forEach method in JavaScript: More Examples


The forEach method in JavaScript is a powerful tool for iterating over arrays. It allows you to apply a callback function to each element in an array, making it a great option for performing actions such as filtering, printing, or manipulating elements. In this blog post, we'll take a look at ten practical examples of using the forEach method to work with arrays in JavaScript.

1. Example of using the forEach method to print each element of an array:

const fruits = ['apple', 'banana', 'cherry'];
fruits.forEach(fruit => console.log(fruit));

In this example, the forEach method is used to iterate over the fruits array and print each element. The callback function takes the current element as an argument, and simply logs it to the console.

2. Example of using the forEach method to sum all elements of an array:

const numbers = [1, 2, 3, 4, 5];
let total = 0;
numbers.forEach(number => {
  total += number;
});
console.log(total); // 15

In this example, the forEach method is used to iterate over the numbers array and sum all the elements. The callback function takes the current element and adds it to the total variable, which is initially set to 0.

3. Example of using the forEach method to create a new array from an existing one:

const numbers = [1, 2, 3, 4, 5];
const doubledNumbers = [];
numbers.forEach(number => {
doubledNumbers.push(number * 2);
});
console.log(doubledNumbers); // [2, 4, 6, 8, 10]

In this example, the forEach method is used to iterate over the numbers array and create a new array containing the double of each element. The callback function takes the current element, multiplies it by 2 and then pushes it to the new array.

4. Example of using the forEach method to find the max element of an array:

const numbers = [1, 2, 3, 4, 5];
let max = numbers[0];
numbers.forEach(number => {
  if (number > max) {
    max = number;
  }
});
console.log(max); // 5

In this example, the forEach method is used to iterate over the numbers array and find the max element. The callback function takes the current element and compares it with the max variable. If the current element is greater than max, it updates the max variable.

5. Example of using the forEach method to calculate the average of an array:

const numbers = [1, 2, 3, 4, 5];
let total = 0;
let count = 0;
numbers.forEach(number => {
  total += number;
  count++;
});
console.log(total / count); // 3

In this example, the forEach method is used to iterate over the numbers array and calculate the average. The callback function takes the current element and adds it to the total variable, and increments the count variable. After the loop, the total and count variables are used to calculate the average.

6. Example of using the forEach method to filter an array:

const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const evenNumbers = [];
numbers.forEach(number => {
  if (number % 2 === 0) {
evenNumbers.push(number);
  }
});
console.log(evenNumbers); // [2, 4, 6, 8, 10]

In this example, the forEach method is used to iterate over the numbers array and filter out the even numbers. The callback function takes the current element, checks if it is divisible by 2 and if it is, it pushes the element to the evenNumbers array.

7. Example of using the forEach method to update elements of an array:

const names = ['John', 'Mike', 'Bob', 'Jane'];
names.forEach((name, index) => {
  names[index] = name.toUpperCase();
});
console.log(names); // ['JOHN', 'MIKE', 'BOB', 'JANE']

In this example, the forEach method is used to iterate over the names array and update each element to uppercase. The callback function takes the current element and its index, and updates the element at that index position to uppercase.

8. Example of using the forEach method to to remove elements from an array:

const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
numbers.forEach((number, index) => {
  if (number > 5) {
numbers.splice(index, 1);
  }
});
console.log(numbers); // [1, 2, 3, 4, 5]

In this example, the forEach method is used to iterate over the numbers array and remove elements greater than 5. The callback function takes the current element and its index, and checks if the element is greater than 5, if it is it uses the splice method to remove that element from the array.

9. Example of using the forEach method to check if an element exists in an array:

const fruits = ['apple', 'banana', 'cherry'];
let exists = false;
fruits.forEach(fruit => {
  if (fruit === 'banana') {
    exists = true;
  }
});
console.log(exists); // true

In this example, the forEach method is used to iterate over the fruits array and check if the element 'banana' exists in the array. The callback function takes the current element and compares it with 'banana', if they are equal it sets the exists variable to true.

10. Example of using the forEach method to check concat array element:

const words = ["hello", "world"];
let concat = "";
words.forEach(word => {
concat += word + " ";
});
console.log(concat); // "hello world "

In this example, we have an array of words and we are using the forEach method to iterate through the array and concatenate each word to a variable called "concat". Once the forEach loop is completed, we log the value of "concat" to the console and it should print "hello world ", which is the concatenation of all words in the array.

In conclusion, the forEach method is a powerful tool in JavaScript for iterating through an array and performing a specific action on each element. It is a more concise and readable way of performing operations on arrays compared to traditional for and while loops. The forEach method does not return a new array and does not stop when it encounters a return statement or throws an error, unlike other looping methods. However, it can be used in conjunction with other array methods such as map, filter, and reduce to perform more complex operations on arrays. It's a very useful method to have in your tool belt as a JavaScript developer, and it's important to be familiar with its syntax and usage.

List of Programs


JS Practical Questions & Answers


JS Practical Project