How to use Arrow Functions in JavaScript
Table of Contents
EcmaScript 6 introduced a new syntax for defining functions, called arrow functions.
Arrow functions are a more concise way of writing functions, and they have some interesting features that make them more flexible than regular functions.
In this post, we'll learn about arrow functions in JavaScript, and how to use them.
How to define arrow functions
As mentioned before, arrow functions are a newer way of defining functions in JavaScript.
First, let's look at the traditional way of defining a function:
JAVASCRIPTfunction add(a, b) {
return a + b;
}
Now, let's look at the same function defined as an arrow function:
JAVASCRIPTconst add = (a, b) => {
return a + b;
};
In essence, the word function
is replaced with an arrow =>
to signify that this is a function.
A key difference is that the first example is defining a function, while the second example is defining a variable that is assigned a function.
This is important to note, because arrow functions are not hoisted like regular functions.
An interesting feature of arrow functions is that they can be defined without the curly braces, if the function only has one statement.
JAVASCRIPTconst add = (a, b) => a + b;
You can use it like any other function:
JAVASCRIPTconst add = (a, b) => a + b;
const sum = add(1, 2);
console.log(sum);
BASH3
Conclusion
In this post, we learned about arrow functions in JavaScript.
Use arrow functions if you're looking for a more concise way of defining functions and don't need hoisting.
Thanks for reading!
- How to Install Node on Windows, macOS and Linux
- Getting Started with Express
- Git Tutorial: Learn how to use Version Control
- Best Visual Studio Code Extensions for 2022
- How to deploy a Deno app using Docker
- Getting Started with Sass
- How to Scrape the Web using Node.js and Puppeteer
- Getting Started with Handlebars.js
- Build a Real-Time Chat App with Node, Express, and Socket.io
- Getting User Location using JavaScript's Geolocation API
- Learn how to build a Slack Bot using Node.js
- Setting Up a Local Web Server using Node.js