In this article, we'll be covering arrow functions and how to implement them in JavaScript. Lets start off by discussing what are arrow functions and how they can be implement in JavaScript.
What Are Arrow Functions?
Arrow functions allow us to define functions with shorter syntax. Arrow functions can be used in replacement of a traditional function function() {}
.
The Syntax
Lets write a function that takes in 2 numbers as parameters a
and b
, then returns the sum.
As a regular function:
function sum(a, b) {
return a + b
}
Now, as an arrow function:
const sum = (a, b) => a + b
You can clearly see how much shorter the syntax is.
When using an arrow function, parameters go at the start in a pair of parenthesis. These are then followed by a =>
which declares an arrow function. After that you would enter {}
and whatever code you wish to run. However when returning a value, you can exclude the curly braces.
Additionally, if there is only one parameter, you can exclude the parenthesis around it.
This would look like this:
const addOne = num => num + 1
If there are no parameters for your function you would simply use an empty pair of parenthesis followed by the usual. Like this:
const sayHello = () => {
console.log("Hello")
}
Arrow functions can be used in replacement of any function use case. For instance, in React, you could use an arrow function to define a functional component rather than a regular function.
Another use case may be as a callback function. For instance, if we have an array of users that looks like this:
const users = [
{
name: "John",
age: 24
},
{
name: "Jane",
age: 32
},
{
name: "Blake",
age: 12
}
]
And we want to use the JavaScript .filter
method to select users who are over 18:
const adults = users.filter(user => user.age > 18)
This is one use case where arrow functions can significantly reduce the amount of code you have to write. This also applies to other array methods like .map
for instance.
Changes To The this
Keyword
In standard functions, the this
keyword represents the object that called the function, which may be a button or even the document. However, in an arrow function, the this
keyword represents the object that defined the arrow function, not the element/object that called the function.
Take Away
I hope you've learned how to begin using arrow functions in JavaScript. ES6 brought a lot of new and improved features to JavaScript, such as arrow functions and classes.
๐ Thanks for reading this article!
If you like what I do and would love to see more related content, follow me on my other social platforms:
GitHub: Blake-K-Yeboah
LinkedIn: Blake-K-Yeboah
You can also show your support by buying me a coffee ๐