Generally many people get confused between arrow and simple function in javascript.There is a slight difference between the two, and that would be the scope they refer to. As so often, it depends. Arrow functions have different behavior than function declarations / expressions. Arrow functions and function declarations / expressions are not equivalent and cannot be replaced blindly, so lets have a look at the differences first:
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 expression
function newObject() {
console.log('Inside `newObject`:', this.foo);
return {
foo: 35,
demo: function() {
console.log('Inside `demo`:', this.foo);
},
};
}
newObject.call({foo: 21}).demo(); // override `this` inside newObject
// Output
Inside `newObject`: 21
Inside `demo`: 35
// Example using a arrow function
function newObject() {
console.log('Inside `newObject`:', this.foo);
return {
foo: 35,
demo: () => console.log('Inside `bar`:', this.foo),
};
}
newObject.call({foo: 21}).demo(); // override `this` inside newObject
// Output
Inside `newObject`: 21
Inside `demo`: 21
In the function expression case, this refers to the object that was created inside the newObject. In the arrow function case, this refers to this of newObject itself. This makes arrow functions useful if you need to access the this of the current environment.
ES2015 distinguishes between functions that are callable and functions that are constructable. If a function is constructable, it can be called with new, i.e. new User(). If a function is callable, it can be called without new (i.e. normal function call). Functions created through function declarations / expressions are both constructable and callable. Arrow functions (and methods) are only callable. class constructors are only constructable.
If you are trying to call a non-callable function or to construct a non-constructable function, you will get a runtime error. Arrow functions cannot be used as constructors and will throw an error when used with new.
var Foo = () => {};
var foo = new Foo(); // TypeError: Foo is not a constructor