ES6 arrow functions traversing an array


question: How to show the elements of an array with arrow functions?

I understand that given an array with elements, I pass the array as a parameter, but what I do not understand, is that it must go in the body of the function?

Can this be done with this type of function? Greetings

asked by Luis Gabriel Fabres 11.03.2017 в 03:06

2 answers


The arrow functions are simply shortcuts to assignable functions or callbacks to maintain the context in which they are called without making explicit% .bind . For example:

class A {
  constructor () { = 'Letra A';

  foo () {
    setTimeout(function () {
    }, 3000);

new A().foo();

The previous example shows one of the problems thanks to which this new notation for functions was proposed. The above code prints undefined because this refers to window and not% A .

The above is solved in ES5 as follows:

setTimeout(function () {
}.bind(this), 3000);

As of ES6, with the arrival of the arrow functions, the solution is simpler:

setTimeout(() => console.log(, 3000);

Answering your question, the way to iterate over an arrangement is the same using ES6:

let names = ['John', 'Martha', 'Leslie'];

names.forEach(name => console.log(name));
answered by 11.03.2017 / 03:21


['a', 2, 'c', 4].forEach(v => console.log(v));

If you would like to evaluate it in ES5 it would be equivalent to:

['a', 2, 'c', 4].forEach(function(v) {
  return console.log(v);
answered by 11.03.2017 в 03:19