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
Function Declaration
Function Declaration is the traditional way to define a function. It is somehow similar to the way we define a function in other programming languages. We start declaring using the keyword “function”. Then we write the function name and the parameters.
Example: Below is an example that illustrates the use of Function Declaration.
Javascript
// Function declaration function add(a, b) { console.log(a + b); } // Calling a function add(2, 3); |
5
After defining a function, we call it whenever the function is required.
Function Expression
Function Expression is another way to define a function in JavaScript. Here we define a function using a variable and store the returned value in that variable.
Example: Below is an example that illustrates the use of Function Expression.
Javascript
// Function Expression const add = function (a, b) { console.log(a + b); } // Calling function add(2, 3); |
5
Here, the whole function is an expression and the returned value is stored in the variable. We use the variable name to call the function.
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.