• 971-553421531
  • info@efaschool.com
  • Dubai(United Arab Emirates)

JavaScript forEach( )

JavaScript forEach()

The forEach() method in javascript is an iterative
method that calls a provided callback function once for each array element in ascending index order.

The callback function is passed three arguments:
1 The current element.
2 the index of the current element
3the array itself

The syntax for the forEach() method is:

array.forEach(callbackfn);

where array is the array to iterate over and callbackfn is the callback function.

The callback function must have the following signature:


          function(currentValue, index, array) {
            // Do something with the current value, index, and array.
          }
        
  • 1 The currentValue argument is the current element in the array.
  • 2 The index argument is the index of the current element, starting from 0.
  • 3 The array argument is the array itself.

Here is an example of how to use the forEach() method:

          
          const array = [1, 2, 3, 4, 5];
      
            array.forEach(function(number) {
                  console.log(number);
              });
        

This code will print the numbers 1, 2, 3, 4, and 5 to the console.

The forEach() method is a convenient way to iterate over an array and perform a task on each element.

It is often used in conjunction with other array methods, such as map() and filter()

Here is an example of how to use the forEach() method with the map() method:

          const array = [1, 2, 3, 4, 5];
      
          const doubledArray = array.map(function(number) {
            return number * 2;
          });
          console.log(doubledArray); // [2, 4, 6, 8, 10]
        

This code first create an array of numbers. Then it uses the map() method to create a new array where each element is the product of the corresponding element in the original array and Finally, it logs the new array to the console.

Leave a Reply

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