Arrow functions vs regular functions in JavaScript
By Flavio Copes
Learn how arrow functions differ from regular functions in JavaScript, from how this is bound to new, arguments, and other practical differences.
Regular functions are the “old school” functions we use since the JavaScript inception:
function run() {
}
They can be run directly:
run()
or they can be assigned to a variable:
const run = function run() {
}
run()
When you do so, the function can also be anonymous:
const run = function () {
}
run()
The function itself has no name, but it takes the name of the variable you assign it to. run.name is 'run', and that is the name you see in the stack trace when there is an error.
Arrow functions, introduced in ES6 in 2015, are always anonymous, like that last form. They get a name the same way, from the variable:
const run = () => {
throw new Error('boom')
}
run.name //'run'
run() //the stack trace shows "run"
The syntax “footprint” is smaller:
const run = () => {
}
run()
If we have one parameter, we can omit the parentheses:
const run = param => {
}
run()
And if we only have one statement, we can also omit the curly braces:
const run = param => 'running'
run()
In this case, the return value is the string 'running'.
Both arrow functions and regular functions can be used as object methods.
Now comes the biggest difference between those 2 functions, and it’s related to how this is bound in a method.
Consider this example:
const car = {
brand: 'Ford',
model: 'Fiesta',
start: function() {
console.log(`Started ${this.brand} ${this.model}`)
},
stop: () => {
console.log(`Stopped ${this.brand} ${this.model}`)
}
}
this in the start() method refers to the object itself.
But in the stop() method, which is an arrow function, it doesn’t.
this is not bound to the object instance. It points to what this points to in the outer scope.
This implies that arrow functions are not suitable to be used for object methods when you want to access this. I wrote more about that in how this works.
A few other differences:
- you cannot use
newwith an arrow function - they have no
argumentsobject (use rest parameters instead) - they have no
prototypeproperty - they cannot be generator functions (
function*still needs a regular function)
Want me to talk about your product? You can sponsor this site.
Related posts about js: