Arrow functions were introduced in ES6. allow us to write shorter function syntax:
below demo function is an arrow function returning hello World String.
The paragraph div content will be replaced by demo function text.
Code Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <p id="div1"></p> <br /> <p id="div2"></p> <script type="text/javascript"> let demo = () => { return "hello World" }; document.getElementById("div1").innerHTML = demo(); </script> </body> </html> |
output: hello Shri
Note: If the function has only one statement, and the statement returns a value, you can remove the brackets and the return keyword.  for multiple statement, the last statement should return value if returning data.
Arrow function with args:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
<html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <p id="div1"></p> <br /> <p id="div2"></p> <script type="text/javascript"> //no arg arrow function let demo = () => { return "hello World"; } // 1 arg arrow function hello = (val) => "Hello " + val; document.getElementById("div1").innerHTML = demo(); document.getElementById("div2").innerHTML = hello("Karthik"); </script> </body> </html> |
Output:
hello World
Hello Karthik
Note: above code , hello arrow function is created with one argument .