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

olu adesina
olu adesina
13,405 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));

2 Answers

Jean-Luc Robitaille
Jean-Luc Robitaille
13,861 Points

It's a shorthand to write an arrow function.

let functionName = (parameters) => {

In the shorthand syntax, if you have only 1 parameter, you can omit the parentheses. And if you only have 1 line of code, or only 1 action in your function body, you can write it without using brackets. So it becomes:

let functionName = parameters => console.log("something");

Check out the course They talk about arrow function.

Juan Hurtado
Juan Hurtado
2,236 Points

Normal way of doing a forEach

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

fruits.forEach(function(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


  • => 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