Arrow Functions vs Regular Functions in JavaScript
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:
1 | function run() { |
Regular functions can be executed directly:
1 | run(); |
Alternatively, they can be assigned to a variable:
1 | const run = function() { |
Regular functions can also be anonymous, meaning they don’t have a name specified:
1 | const run = function() { |
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:
1 | const run = () => { |
If the function has only one parameter, you can omit the parentheses:
1 | const run = param => { |
Similarly, if the function has only one statement, you can omit the curly braces:
1 | const run = param => 'running'; |
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:
1 | const car = { |
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