What is React Arrow function?



Arrow functions are introduced in ES6 , which provides you a more accurate way to write the functions in JavaScript . 

They allow us to write smaller function syntax. Arrow functions make your code more readable and structured.


As in before ES6 we always write a function like below


function add(){ 
console.log(2+2);
}

But in ES6 we can write a function like below, In this we can save a function to a variable or constant.


let add = () =>{ 
console.log(2+2);
}
Now syntax of arrow function is.

let function = (arg1, arg2. . . .) =>{ 
statement...
}
If the body has single statement or expression, you can write arrow function as below

let myFunction = (arg1, arg2, ...argN) => expression
Real example to write in single line.


let x = (x, y) => x * y;
Now we will check some example of arrow function.

1. Function with No Argument 

let greet = () => console.log('Welcome User');
Output
Hello
2. Function with One Argument 
let greet = x => console.log("Welcome "+x);
Output by calling greet("TechnicalHub")
Welcome TechnicalHub
3. Function as an Expression


let your_age = 5; 
let welcome = (your_age < 18) ? () =>
console.log('Not allowed') : () =>
console.log('You welcome');

Output by calling welcome();

Not allowed









Post a Comment

Previous Post Next Post