1

Recently I have come across with another way of writing a function expression, like this: setTimeout(() =>{/*code*/},1000); as opposed to: setTimeout(function(){/*code*/},1000);

What is the benefit of using () = > rather than function(){}

Can I use it all the time or only in the certain situations?

Thanks.

2 Answers 2

3

There are a few differences between arrow functions and anonymous function declarations:

  • Arrow functions don't have a prototype-property.
  • Arrow functions cannot be constructed
  • Arrow functions don't bind a this-value, so you'll get the this-instance of the parent scope
  • Arrow functions don't have access to the special arguments-object

For your use case, it's difficult to say whether it'll make a difference because we can't see the code, but my guess is it won't make a difference.

0
3

The major benefit is the shorter syntax:

var sequence = source.map(t => t.length).filter(s => s > 5);

is shorter and more readable than:

var sequence = source
    .map(function (t) { return t.length; })
    .filter(function (s) { return s > 5; });

An arrow function expression has a shorter syntax compared to function expressions and lexically binds the this value

Source: MDN

0

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.