Arrow Functions
Arrow functions are been introduced in the ES6 version of JavaScript. It is used to shorten the code. Here we do not use the “function” keyword and use the arrow symbol.
Example: Below is the example that illustrates the use of the Arrow Function.
Javascript
// Single line of code let add = (a, b) => a + b; console.log(add(3, 2)); |
5
This shortens the code to a single line compared to other approaches. In a single line of code, the function returns implicitly.
Note: When there is a need to include multiple lines of code we use brackets. Also, when there are multiple lines of code in the bracket we should write return explicitly to return the value from the function.
Example: This is an example with multiple lines of code in arrow function
Javascript
// Multiple line of code const great = (a, b) => { if (a > b) return "a is greater" ; else return "b is greater" ; } console.log(great(3, 5)); |
b is greater
Please go through this Difference between ‘function declaration’ and ‘function expression’ in JavaScript to check the differences between them.
Different ways of writing functions in JavaScript
JavaScript Function is a block of code that is designed to perform a task and executed when it is been called or invoked.
Below are the ways of writing functions in JavaScript:
Table of Content
- Function Declaration
- Function Expression
- Arrow Functions