- Regular Functions / Function Declarations -
- Anonymous Functions / Function Expressions are just function declarations without a name. Every time you write the function keyword, anywhere in your code, giving it a name right after is optional. Omitting the name makes the function, well, anonymous.
- Arrow Functions provide lexical binding, meaning you get the control back on the value of this inside the function’s body. By getting the control back, I mean that it’s fairly easy to know which object this refers to just by looking at the code where your arrow function is defined (and not called)
Code Examples
|
Function Type |
Code Example |
|---|---|
|
Regular Function |
|
|
Anonymous Function |
|
|
Arrow Function |
|
|
Function Type |
Code Example |
|---|---|
|
Regular Function |
|
|
Anonymous Function |
|
|
Arrow Function |
|
|
Function Type |
Code Example |
|---|---|
|
Regular Function |
|
|
Anonymous Function |
|
|
Arrow Function |
|
Differences Between Them
arrow function does not do ‘this’ binding, as shown below
var user = {
name: "Marcus Chiu",
regular() {
console.log(this.name); // 'this' binding works here
},
anon: function () {
console.log(this.name); // 'this' binding works here
},
arrow: () => {
console.log(this.name); // 'this' binding FAILS here
},
};
user.regular(); // outputs 'Marcus Chiu'
user.anon(); // outputs 'Marcus Chiu'
user.arrow(); // outputs nothing