Are 'Arrow Functions' and 'Functions' equivalent / interchangeable? Are 'Arrow Functions' and 'Functions' equivalent / interchangeable? javascript javascript

Are 'Arrow Functions' and 'Functions' equivalent / interchangeable?


tl;dr: No! Arrow functions and function declarations / expressions are not equivalent and cannot be replaced blindly.
If the function you want to replace does not use this, arguments and is not called with new, then yes.


As so often: it depends. Arrow functions have different behavior than function declarations / expressions, so let's have a look at the differences first:

1. Lexical this and arguments

Arrow functions don't have their own this or arguments binding. Instead, those identifiers are resolved in the lexical scope like any other variable. That means that inside an arrow function, this and arguments refer to the values of this and arguments in the environment the arrow function is defined in (i.e. "outside" the arrow function):

// Example using a function expressionfunction createObject() {  console.log('Inside `createObject`:', this.foo);  return {    foo: 42,    bar: function() {      console.log('Inside `bar`:', this.foo);    },  };}createObject.call({foo: 21}).bar(); // override `this` inside createObject