Arrow functions are a cleaner way of writing functions in Javascript.
There are some differences between normal javaScript functions and arrow functions.
this
this
keyword in arrow functions refers to the scope where it is defined
For example:
const hello = () => console.log(this);
hello();
Output:
here this refers to the window object, as it is defined in the global
scope.
Syntax
A typical arrow function syntax looks like this
identifier functionName = (param1, paramN) => { statements; }
A nice example would be
let hello = (name) => { console.log("Hello" + name ) }
Although it is the way to write an arrow function. It can be made cleaner and readable.
Here are some conditions where arrow functions can be made more beautiful.
Single line Arrow functions
1 . It does not require parenthesis {}
For example, you could write a single arrow function as
let hello = () => console.log("Hello" );
2 . It does not require the return
keyword
For example
let sum = () => a+b; //returns a+b
is equivalent to
let sum = () => {return a+b;} //returns a+b
If you use parenthesis in a single statement function then you should write the
return
keyword explicitly.
let sum = () => { a+b; } //returns undefined
let sum = () => a+b; //returns a + b
Parameters
1 . No parameters
It is mandatory to provide () even in case of no parameters
Example:
let hello= () => console.log("Hello");
2 . Single Parameters
You don't have to write () if there is only a single parameter.
For example
let hello = name => console.log("Hello " + name);
This single parameter and statement arrow function looks so beautiful 😍👌
3 . Multiple Parameters
You have to use () in case if you have more than 1 parameters
For Example
let hello = (name,caste) => console.log(`Hello ${name} ${caste}`);
Points to be Noted:
this
inside arrow function refers to the scope where the function is definedArrow function does not require
{}
if only a single statement.Single statement Arrow function returns its statement if
{ }
is not used.return
keyword should be used explicitly for the single statement arrow function to return value if{ }
is used.Arrow function doesn't require () if only a single parameter.
Stay updated with this series Javascript 1o1 .
Top comments (0)