-2

There are 10 elements in an array. What to do if i want to show the first 5 elements from the array by using forEach loop?

let arrays =[1, 2, 4, 6, 7, 44, 5, 7, 6]
 arrays.forEach(array =>{}) //
Jabed
  • 15
  • 5

1 Answers1

3

To show the first 5 elements from the array by using forEach loop, you can use if statement

const arrays = [1, 2, 4, 6, 7, 44, 5, 7, 6];

arrays.forEach(function(value, index, array) {

    if(index <= 4) {
        document.write(value + "<br>");
    }

});

Where parameters:

  • Index = The index of the current element.
  • Value = The value of the current element.
  • Array = The array of the current element.

https://www.w3schools.com/jsref/jsref_foreach.asp https://www.w3schools.com/js/js_if_else.asp