CodePark/ questions / this & binding
START PRACTICINGPRACTICE
Frontend question · JavaScript › this & binding

How do arrow functions differ from regular functions?

The main difference is this. An arrow function has no this of its own. It uses the this of the surrounding code where it was defined. call, apply and bind cannot change it.

This makes arrows a good choice for callbacks inside methods. It makes them a bad choice for object methods that need this to be the object.

Arrow functions also lack some things that regular functions have:

  • no own arguments object, so use rest parameters like (...args) instead
  • no super and no new.target
  • they cannot be constructors, so calling them with new throws a TypeError
  • no prototype property
  • they cannot be generators

The syntax is also shorter. A concise body returns its value without the return keyword: x => x * 2. To return an object literal this way, wrap it in parentheses: () => ({ a: 1 }).

  • An arrow function takes this from where it was written, not from how it is called.
  • Arrow functions have no arguments, super, new.target or prototype.
  • Arrow functions cannot be used with new.
  • They are good for callbacks, but poor for object methods and prototype methods.
  • A concise body like x => x * 2 returns its value automatically.