Arrow function is a new syntax for writing ordinary function expressions.
Arrow functions are defined using the fat arrow (=>) notation.
It provides a more concise syntax for writing function expressions by removing the "function" and "return" keywords.
We can also skip the parenthesis in the case when there is exactly one parameter,
These function expressions make your code more readable, and more modern.
In ES5, we had to use the below approach.
$('.button).click(function(event){
//Code
});
In ES6, we had to use the below approach.
$('.button).click((event) => {
//Code
});
Example 1: Arrow Function with No Argument
You should use empty parentheses if a function doesn't take any argument.
const name=() => console.log(‘Hello’);
name();
// Output : Hello
Example 2: Arrow Function with One Argument
If a function has only one argument, you can omit the parentheses
const name=x=>console.log(x);
name(‘Hello’);
// Output : Hello
Example 3: Arrow Function as an expression
You can also dynamically create a function and use it as an expression
let age = 5;
let show=(age < 18) ?
()=> console.log(‘Not Adult’) :
()=> console.log(‘Adult’) ;
show();
// Output : Not Adult
Example 4: Multiline Arrow Functions
If a function body has multiple statements, you need to put them inside curly brackets { }
let multi = (a,b) => {
let result = a * b;
return result;
}
let result1=multi(3,2);
console.log(result1);
// Output : 6