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?

4
  • 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. Commented May 7, 2018 at 22:38
  • Possible duplicate of Arrow function vs function declaration / expressions: Are they equivalent / exchangeable? Commented May 8, 2018 at 3:28
  • Thanks @jfriend00. I will study more about arrow functions. Commented May 8, 2018 at 8:59
  • Thanks @FelixKling for the reference. It helped a lot. Commented May 8, 2018 at 8:59

1 Answer 1

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);

Sign up to request clarification or add additional context in comments.

2 Comments

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.
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.