DEV Community

Cover image for Javascript 1o1 - Arrow Functions
Anjal Binayak Adhikari
Anjal Binayak Adhikari

Posted on

Javascript 1o1 - Arrow Functions

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();
Enter fullscreen mode Exit fullscreen mode

Output:
arrow-function-output-1.png
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; } 
Enter fullscreen mode Exit fullscreen mode

A nice example would be

let hello = (name) => { console.log("Hello" + name ) }
Enter fullscreen mode Exit fullscreen mode

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" );
Enter fullscreen mode Exit fullscreen mode

2 . It does not require the return keyword

For example

let sum = () => a+b;  //returns a+b
Enter fullscreen mode Exit fullscreen mode

is equivalent to

let sum = () => {return a+b;} //returns a+b
Enter fullscreen mode Exit fullscreen mode

If you use parenthesis in a single statement function then you should write the return keyword explicitly.

let sum = () => { a+b; }  //returns undefined
Enter fullscreen mode Exit fullscreen mode
let sum = () =>  a+b;   //returns a + b
Enter fullscreen mode Exit fullscreen mode

Parameters

1 . No parameters

It is mandatory to provide () even in case of no parameters
Example:

let hello= () => console.log("Hello");
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

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}`);
Enter fullscreen mode Exit fullscreen mode

Points to be Noted:

  1. this inside arrow function refers to the scope where the function is defined

  2. Arrow function does not require {} if only a single statement.

  3. Single statement Arrow function returns its statement if { } is not used.

  4. return keyword should be used explicitly for the single statement arrow function to return value if { } is used.

  5. Arrow function doesn't require () if only a single parameter.

  6. Stay updated with this series Javascript 1o1 .

Top comments (0)