0

I'm trying to pass in an additional parameter to the callback function in a map. The value is not passed when I use es6 syntax for callback function and in map.

Here is the es6 map and callback function

const convertEvents = action.payload.map(item => convertEvent(item), { role: 'teacher' });

const convertEvent = (item) => {
    console.log('----------convertEvent role----------');
    console.log(this.role);
    return item;
};

But when I used old javascript syntax the value is passed and the code works correctly

const convertEvents = action.payload.map(convertEventRole, { role: 'teacher' });

function convertEventRole(item) {
    console.log('----------convertEvent role----------');
    console.log(this.role);
    return item;
}

Can you tell me why the es6 code didn't work?

Yasith Prabuddhaka
  • 859
  • 1
  • 11
  • 17
  • I'd suggest looking up with the main feature of `=>` is in ES6 (hint it has to do with the value of `this`). It is not just a shortcut. It has a functionality difference too. There are hundreds of articles on this feature you can read. – jfriend00 May 07 '18 at 22:38
  • Possible duplicate of [Arrow function vs function declaration / expressions: Are they equivalent / exchangeable?](https://stackoverflow.com/questions/34361379/arrow-function-vs-function-declaration-expressions-are-they-equivalent-exch) – Felix Kling May 08 '18 at 03:28
  • Thanks @jfriend00. I will study more about arrow functions. – Yasith Prabuddhaka May 08 '18 at 08:59
  • Thanks @FelixKling for the reference. It helped a lot. – Yasith Prabuddhaka May 08 '18 at 08:59

1 Answers1

3

The 2nd parameter passed to Array.map() is the thisArg, which is:

Value to use as this when executing callback.

With a standard JS function, this is defined by execution context, but you can change it using Function.bind(), and other methods.

An arrow function this is defined by the context in which it's declared, and thus cannot be changed. That's why you can use the assigned thisArg with an arrow function.

You can approximate the functionality using partial application and IIFE:

const arr = [1, 2, 3];

const result = arr.map(((m) => (n) => n + m)(5));

console.log(result);
Ori Drori
  • 183,571
  • 29
  • 224
  • 209
  • Thanks a lot for this explanation. I have been replacing all my functions with new es6 syntax and now I know there is a clear difference between them. I should read more about arrow functions I guess. – Yasith Prabuddhaka May 08 '18 at 08:57
  • Welcome :) The main feature of arrow functions (beyond being shorter) is the scope of `this`, so you should read about lexical scoping. This seems to be a nice article about [arrow functions and lexical scope](https://toddmotto.com/es6-arrow-functions-syntaxes-and-lexical-scoping/). – Ori Drori May 08 '18 at 09:02