Good/notGood to use the function that way | map(), filter()

Hello JS people,
While learning JS I have seen a function has been used two ways as shown below:

//1st way
var new_s = s.myFilter(function(item) {
  return item % 2 === 1;
});

or,

//2nd way
var new_s = s.myFilter(item => item % 2 === 1);

As far as i know both ways are same and I am comfortable with the 2nd way. But i am confused about something.
Are those both functions work same for all the cases?
Is it OK if i practice using function like the 2nd one?

Note: I’m learning JS.
Thanks.

There is some good references on MDN

Generally, people prefer to use ‘arrow function’ notation for the callback functions for map, filter, etc because its shorter. You’ll probably see it much more, so I think it’s a good idea to get used to reading and writing arrow functions for your callbacks.

2 Likes

Jeremy is right, of course. Just to expand a little:

Are those both functions work same for all the cases?

In this case, yes. In all cases, usually, but not always. There are a few subtle differences.

Is it OK if i practice using function like the 2nd one?

I tend to default to arrow functions. I really don’t bother with standard functions unless I’m in someone else’s code that uses them heavily or for generator functions (which is kind of its own thing anyway).

Learn both, learn the subtle differences, but you’ll probably see more arrow functions than standard functions in new code, imho.

You see a lot more standard functions in teaching materials than in new code, I think. A lot of teaching material still make a big distinction between pre and post ES6.

1 Like

No, they do not. You have to keep the rules of this and arrow functions in mind.

Example
<div class="container">
  <h1>Title</h1>
</div>
const container = document.querySelector(".container");

container.addEventListener("click", ({ currentTarget }) => {
  console.log(this); // Window
  console.log(currentTarget); // <div class="container"></div>
});
const container = document.querySelector(".container");

container.addEventListener("click", function({ currentTarget }) {
  console.log(this); // <div class="container"></div>
  console.log(currentTarget); // <div class="container"></div>
});

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.