There are two major benefits of using Arrow functions in JavaScript. One is that it’s a shorter syntax and thus requires less code. And another benefit is that it removes the several pain points associated with this operator.
ES5 function has the following syntax:
function square(a) {
return a * a;
}
In ES6, the same Arrow function
let square = (a) => { return a * a; }
can skip curly braces {}
and the return
statement:
let square = (a) => a * a
Arrow functions are best for callbacks or methods like map, reduce, or forEach.
Arrow function in JavaScript benefits
Simple example code using the arrow function to check whether a number entered by the user is greater than 10 or not.
<!DOCTYPE html>
<html>
<body>
<script>
let checkNumber = (num) => num > 10 ?
console.log(num, "Yes") : console.log(num, "No");
checkNumber(5);
checkNumber(10);
checkNumber(20);
checkNumber(30);
</script>
</body>
</html>
Output:
Performing different operations on array elements.
<script>
let array = [1, 3, 5];
let sum = array.reduce((a, b) => a + b);
console.log(sum); // 54
let mul = array.map((element) => element * 10);
console.log(mul); // [ 10, 30, 500 ]
let filt = array.filter((element) => element % 2 === 0);
console.log(filt); // [ 50 ]
</script>
- Arrow function reduce code and makes the mode more readable.
- Arrow function syntax automatically binds “this” to the surrounding code’s context.
- Writing the arrow => is more flexible as compared with the function keyword.
Do comment if you have any doubts or suggestions on this JS function topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version