snippetjavascriptTip
What are the differences between arrow functions and regular functions in JavaScript?
Viewed 0 times
javascriptwhatandbetweendifferencestheregularfunctionsarroware
Problem
JavaScript's arrow functions might seem the same as regular functions on the surface, but they have some very important differences:
- Syntactical differences
thisvalue (execution context)- Usage as methods
- Usage as constructors
Solution
const square = a => a * a;
// Equivalent regular function
function square(a) {
return a * a;
}thisvalue (execution context)- Usage as methods
- Usage as constructors
argumentsbinding
The first and most obvious difference between arrow functions and regular functions is their syntax. Not only do they look different, but arrow functions also provide an implicit return shorthand and allow parenthesis around a single argument to be omitted.
Inside a regular function, execution context (i.e. the value of
this) is dynamic. This means that the value of this depends on how the function was invoked (simple invocation, method invocation, indirect invocation or constructor invocation). On the other hand, an arrow function does not define its own execution context. This results in an arrow function's this being resolved lexically (i.e. the scope in which the arrow function was defined).Code Snippets
const square = a => a * a;
// Equivalent regular function
function square(a) {
return a * a;
}function logThis() {
console.log(this);
}
document.addEventListener('click', logThis);
// `this` refers to the document
const logThisArrow = () => {
console.log(this);
};
document.addEventListener('click', logThisArrow);
// `this` refers to the global objectfunction logThis() {
console.log(this);
}
logThis.call(42); // Logs: 42
const logThisArrow = () => {
console.log(this);
};
logThisArrow.call(42); // Logs the global objectContext
From 30-seconds-of-code: arrow-regular-function-differences
Revisions (0)
No revisions yet.