Arrow function and Normal Function
How does the arrow function differently from the normal function?
Let’s understand the first normal function (Function declaration) and Function expression.
Function
The function is the building block of code for a particular statement that performs or calculates a value, and which can be called anywhere in your program.
Normal Function
Traditional way to define a function in javaScript .
function printName() {
return 'The Resources';
}
console.log(printName());In the above program
A normal function is defined with the function keyword.
printName() : - function name with parenthesis holds functions parameter
{ } Inside curly braces called function body
at the end printName() function invocation
The functions are first a class citizen in JavaScript.
In JavaScript Programming, You can treat the function as a value, which means you can assign it to a variable, pass through a function argument, and return from another function.
Function expression
When you assign a function in a variable.
const printName = function () {
console.log('The Resources'); // The Resources
};
printName();
We are using an anonymous function.
Anonymous Function is a function that does not have any name associated with it .
Arrow Function
The arrow function was introduced in ES6 2015.
It is a new way to declare functions in javaScript Anonymously.
Arrow functions are shorter, clean form of normal function.
Example from the above function.
const printName = () => {
console.log('The Resources');
};
printName();But Arrow function has more advantages, Let's look into it
// Suppose we have only one argument
const addFive = a => a + 5;
console.log(addFive(5));
// You don't need to give parenthesis for one argument, and curly braces
// Also, you don't need to give a return keyword for a single expression
// But for multiline express
//Sometimes we need some complex expression, in case we need curly braces and also
// needs return keyword
const multiple = (a, b) => {
let result;
result = a * b;
return result;
};
console.log(multiple(5, 8));So, Basically, Arrow functions are handy for simple actions, and especially for one-liners operation with array methods.
const array = [5, 6, 7, 8, 9];
const newArray = array.map( element => element * 5);
console.log(newArray); //[25, 30, 35, 40, 45]Last updated