In JavaScript, arrow functions and regular functions serve the same purpose but have some key differences. Let’s explore what sets them apart.
Regular functions have been used since the inception of JavaScript. They can be defined in the following ways:
function run() {
// code here
}
Regular functions can be executed directly:
run();
Alternatively, they can be assigned to a variable:
const run = function() {
// code here
};
run();
Regular functions can also be anonymous, meaning they don’t have a name specified:
const run = function() {
// code here
};
run();
However, in the stack trace that appears during error handling, the function name won’t be visible.
Arrow functions were introduced in ES6 in 2015 and have a more concise syntax. They don’t have a name and are always anonymous. Here’s how they are defined:
const run = () => {
// code here
};
run();
If the function has only one parameter, you can omit the parentheses:
const run = param => {
// code here
};
run();
Similarly, if the function has only one statement, you can omit the curly braces:
const run = param => 'running';
run();
In this case, the return value will be the string 'running'
.
Both arrow functions and regular functions can be used as object methods. However, the crucial difference between them lies in how this
is handled in a method.
Consider the following example:
const car = {
brand: 'Ford',
model: 'Fiesta',
start: function() {
console.log(`Started ${this.brand} ${this.model}`);
},
stop: () => {
console.log(`Stopped ${this.brand} ${this.model}`);
}
};
In the start()
method, this
refers to the object itself. However, in the stop()
method, which is an arrow function, this
does not refer to the object instance. Instead, it points to whatever this
points to in the outer scope.
This means that arrow functions are not suitable for use as object methods when you need to access this
.
Tags: JavaScript, arrow functions, regular functions, object methods, this