Difference in function expression

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?


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.


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


Trả lời

Email của bạn sẽ không được hiển thị công khai. Các trường bắt buộc được đánh dấu *