Arrow function in javascript uses => arrow symbol and no function keyword. due to this, syntax become shorter and more readable.
Syntax
function_name = (arg1, arg2) =>{
// set of statements
}
arg1, arg2 are arguments which are optional.
Same function with Normal or traditional function and Arrow Function
Normal or traditional function
<script>
function sayHello{
document.write("Hello from traditional function");
}
sayHello();
</script>
Arrow function Example
<script>
sayHello = () =>{
document.write("Hello from Arrow function");
}
sayHello();
</script>
You can easily observe the difference in Arrow function, no function keyword is used and only => is used.
Arrow functions with parameters
Arrow functions can accept parameters as traditional functions.
Single parameters Arrow functions
<script>
sayHello = (a) => {
document.write(a);
}
sayHello(20);
</script>
No parenthesis with one parameter in Arrow function
<script>
sayHello = a =>{
document.write(a);
}
sayHello(20);
</script>
Single parameters is allowed, without parenthesis() in arrow function,
Multiple parameters Arrow functions
In arrow function, more than one parameters can be passed, but for multiple parameters, parenthesis is mandatory.
<script>
sayHello = (a,b) =>{
document.write(a+b);
}
sayHello(20,10);
</script>
No curly braces with one statement in Arrow function
Arrow function allows no curly braces {}, if only single statement is used.
<script>
sayHello = a =>
document.write(a);
sayHello(120);
</script>
By default Arrow function, Returns value with one statement
Single statements in arrow function automatically or by default returns value.
<script>
sayHello = () => "Hello";
document.write(sayHello());
</script>
Above example, Arrow function sayHello will return Hello automatically.
Multiple statements in Arrow function
In multiline or multiple statements in arrow functions, curly braces are mandatory.
<script>
sayHello = () =>{
a = 20;
b = 30;
c = a + b;
document.write(c);
}
sayHello();
</script>