Javascript Arrow is an alternative syntax to the old regular function.
There is two main use case of using a javascript arrow function. The first is that it makes the code shorter and concise like below.
No argument
// Regular Function
function sayHello() {
return 'Hello'
}
// Arrow Function
const sayHello = () => 'Hello'
One argument
// Regular Function
function addTen(number) {
return number + 10
}
// Arrow Function
// Notice that we can remove the parenthesis around the parameter when argument is just one. It is optional.
const addTen = num => number + 10
Two or more arguments with multiple function body statements. We have to keep the curly braces and the return keyword for multiple function body statements.
// Regular Function
function addTen(number1, number2) {
const ten = 10 // function body line #1
return number1 + number2 + 10 // function body line #2
}
// Arrow Function
const addTen = (number1, number2) => {
const ten = 10
return number1 + number2 + 10
}
The second use case of the arrow function is to handle the scope better. Let see a very simple example.
const person = {
myName: ‘John Doe’,
sayName () {
setTimeout(function() {
console.log(`Hi, ${this.myName}`)
}, 1000)
}
}
When we invoke
person.sayName()
We expect to see
Hi, John Doe
Unfortunately, will get below.
It is because the function is pointing to the window object and window object doesn't have a method called sayName.
Hi, undefined
To fix the context issue, engineers use these workarounds
Fix #1:
// Save the context and use that context
const person = {
myName: ‘John Doe’,
sayName () {
const _this = this
setTimeout(function() {
console.log(`Hi, ${_this.myName}`)
}, 1000)
}
}
Fix #2:
// Use bind to ensure that context is set and kept
const person = {
myName: ‘John Doe’,
sayName () {
setTimeout(function() {
console.log(`Hi, ${this.myName}`)
}.bind(this), 1000)
}
}
Fix #3 - Modern solution
Arrow function behaves like a variable, it establishes the value of this (context) where the arrow function is created
// Using Arrow Function.
const person = {
myName: ‘John Doe’,
sayName () {
setTimeout(() => console.log(`Hi, ${this.myName}`), 1000)
}
}
If you prefer to watch a 5 minutes video instead, below is the link
If you want to support me - Buy Me A Coffee
Top comments (1)
Function declarations are hoisted while function expressions are not.
Some comments have been hidden by the post's author - find out more