xxxxxxxxxx
It is important to note that arrow functions are anonymous, which means that they are not named.
This anonymity creates some issues:
Harder to debug
When you get an error, you will not be able to trace the name of the function or the exact line number where it occurred.
2. No self-referencing
If your function needs to have a self-reference at any point (e.g. recursion, event handler that needs to unbind), it will not work.
Main benefit: No binding of ‘this’
xxxxxxxxxx
// Normal Function in JavaScript
function Welcome(){
console.log("Normal function");
}
// Arrow Function
const Welcome = () => {
console.log("Normal function");
}
xxxxxxxxxx
///////
//JavaScript Function Declarations
///////
//4th (arrow function)
hello4 = (name) => { return ("Hello " + name); }
//OR
hello5 = (name) => { return (`Hello new ${name}`) }
//1st (simple function)
function hello1() {
return "Hello simple function";
}
//2nd (functino expression)
hello2 = function() {
return "Hello functino expression";
}
// 3rd ( IMMEDIATELY INVOKED FUNCTION EXPRESSIONS (llFE))
hello3 = (function() {
return "Hello IMMEDIATELY INVOKED FUNCTION EXPRESSIONS (llFE)";
}())
xxxxxxxxxx
// Non Arrow (standard way)
let add = function(x,y) {
return x + y;
}
console.log(add(10,20)); // 30
// Arrow style
let add = (x,y) => x + y;
console.log(add(10,20)); // 30;
// You can still encapsulate
let add = (x, y) => { return x + y; };
xxxxxxxxxx
// Function in JavaScript
function regular(){
console.log("regular function");
}
regular(); //regular function
// Arrow Function
const arrow = () => console.log("Arrow function");
arrow(); //Arrow function
xxxxxxxxxx
// arrow function shorten way to write function
//it make easy to write callback function
const arrowFunction = names.map((name)=> {
return name.length <6 ? "long name" :"short name"
})
//if we have one parameter in callback function we don't need to add parenthesis ()
//if there is only one code logic and return value then we can remove return and {}
const arrowFunction = names.map(name=> name.length<10 ? "long name" :"short name" )
xxxxxxxxxx
// Traditional Function
function (a, b){
return a + b + 100;
}
// Arrow Function
(a, b) => a + b + 100;
// Traditional Function (no arguments)
let a = 4;
let b = 2;
function (){
return a + b + 100;
}
// Arrow Function (no arguments)
let a = 4;
let b = 2;
() => a + b + 100;