JavaScript JavaScript Array Iteration Methods Array Iteration `for` vs forEach()

olu adesina
PRO
olu adesina
Pro Student 7,183 Points

how does the => operator work in this forEach() method

how does the => operator work in this case never seen it used like this before

const fruits = ['apple', 'pear', 'cherry'];

fruits.forEach(fruit => console.log(fruit));

1 Answer

Juan Hurtado
Juan Hurtado
1,764 Points

Normal way of doing a forEach

const fruits = ['apple', 'pear', 'cherry'];

fruits.forEach(function(fruit) {
    console.log(fruit)
});

Using the => operator you are removing a few things from the way of writing the callback:

  • function keyword
  • parenthesis around the argument name
  • curly braces surrounding the body of the callback e.g. console.log(fruit)
  • replacing the callback console.log in the same line

Adding:

  • => operator to denote what the callback returns

The purpose is to do the same but more concise.

Bear in mind both ways do the exact same thing