In this JavaScript lesson we are going to learn about JavaScript Arrow Function, Arrow functions are also called fat arrow functions, they are one line functions and are much like Lambda functions in programming languages like Java and Python. it is a feature on JavaScript ES6.
Now first let’s create our regular function. it is a simple function that takes name as argument and we want to print that name in the output.
1 2 3 4 5 |
function display(name) { console.log(name) } display("Parwiz") |
We have another type of function that is called anonymous function.
1 2 3 4 5 |
const display = function(name) { console.log(name) } display("John Doe") |
Now let’s create an example of arrow function in JavaScript.
1 2 3 4 5 |
const display = (name) => { console.log(`My name is ${name}`) } display("Parwiz"); |
You can also make it simpler.
1 2 3 |
const display = (name) => console.log(`My name is ${name}`) display("Parwiz"); |
Now let’s create another arrow function that finds the factorial of a number.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
const factorial = (n) => { let product = 1; for (let i = 1; i <=n; i++ ) { product *= i; } return product; } console.log(factorial(5)); |
JavaScript Arrow Function Features
As we already have mentioned that Arrow functions are feature that provide shorter syntax for writing function expressions. they are particularly useful for writing shorter and more concise functions. these are some features of arrow functions with code examples:
- Shorter Syntax: Arrow functions have a shorter syntax than traditional function expressions.
1 2 3 4 5 6 7 |
// Traditional function expression const sum = function (a, b) { return a + b; }; // Arrow function expression const sum = (a, b) => a + b; |
In this example, the sum function is defined using both a traditional function expression and an arrow function expression. the arrow function expression is more concise and easier to read.
- Implicit Return: Arrow functions have an implicit return statement, meaning that the value of the expression is returned without needing to use the return keyword.
1 2 3 4 5 6 7 |
// Traditional function expression const double = function (x) { return x * 2; }; // Arrow function expression const double = x => |