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

olu adesina
PRO
olu adesina
Pro Student 10,288 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,859 Points

It's a shorthand to write an arrow function.

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

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 teamtreehouse.com/library/getting-started-with-es2015-2 They talk about arrow function.

Juan Hurtado
Juan Hurtado
2,228 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