In JavaScript, you can define functions in many ways.
The first, usual way, is by using the function
keyword:
// Function declaration
function greet(who) {
return `Hello, ${who}!`;
}
// Function expression
const greet = function(who) {
return `Hello, ${who}`;
}
The function declaration and function expression I’m going to reference as regular function.
The second way, available starting ES2015, is the arrow function syntax:
const greet = (who) => {
return `Hello, ${who}!`;
}
While both the regular and arrow syntaxes define functions, when would you choose one instead of another? That’s a good question.
In this post, I’m going to show the main differences between the two, so you could choose the right syntax for your needs.
Inside of a regular JavaScript function, this
value (aka the execution context) is dynamic.
The dynamic context means that the value of this
depends on how the function is invoked. In JavaScript, there are 4 ways you can invoke a regular function.
During a simple invocation the value of this
equals to the global object (or undefined
if the function runs in strict mode):
function myFunction() {
console.log(this);
}
// Simple invocation
myFunction(); // logs global object (window)
During a method invocation the value of this
is the object owning the method:
const myObject = {
method() {
console.log(this);
}
};
// Method invocation
myObject.method(); // logs myObject
#javascript #function #arrow function