𝕭𝖎𝖓𝖆𝔂𝓪𝓴 𝕭𝖑𝖔𝖌

𝕭𝖎𝖓𝖆𝔂𝓪𝓴 𝕭𝖑𝖔𝖌

Javascript Arrow Functions ( ) => { }

Javascript Arrow Functions ( ) => { }

Subscribe to my newsletter and never miss my upcoming articles

Arrow functions are a cleaner way of writing functions in Javascript. There are some differences between normal javaScript functions and arrow functions.


this keyword in arrow functions refers to the scope where it is defined For example:

const hello = () => console.log(this);

Output: arrow-function-output-1.png here this refers to the window object, as it is defined in the global scope.


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


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:

  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 .
Share this