What is arrow function in JavaScript?

In this tutorial, I am going to discuss what is arrow function in JavaScript.  In the previous tutorial, I have discussed what functions in JavaScript are this time it’s all about arrow functions.

What is arrow function in JavaScript?

An arrow function is a function that was introduced in ES6 or ECMAScript 2015.

  • It allows you to write normal or user-defined functions.
  • It was introduced in ES6 or ECMAScript 2015.
  • It allows you to write normal or user-defined functions in JavaScript in a concise way.
  • It has a shorter syntax compared to normal or regular functions in JavaScript. It is mainly used in ReactJS, AngularJS, and VueJS.

what is arrow function in javascript

An arrow function is always an anonymous function. It is called or invoked using a variable name followed by parentheses.

Syntax

let variable_name = (param1, param2, ….) =>{ // statements };

Where param1, param2,…. are parameters or arguments or are optional and => is an arrow operator, that’s why it is called an arrow function.

Example

let hello = () => {
    let name = 'Rohit';
    console.log ('Hello',name);
}
hello (); // function call

Here, we can check the type of hello or variable using the typeof operator in JavaScript.
console.log (typeof fun); // function
In the case of single-line function definition or body, the return keyword and curly braces ({}) are optional.

const msg = () =>; 'Hello,World';
msg (); // function call

In the case of only one argument or parameter, parentheses are optional. But in the case of multiple parameters or arguments, parentheses are mandatory.

// single parameter,
const num = a =>; console.log (a);
num (4); // function call
// multiple parameters
const multiplyAandB = (a, b) => a * b;
console.log (multiplyAandB (4, 5)); // 20

How to pass Default Parameters to The arrow Function?

Like normal or regular functions, we can also pass a default parameter or argument to the arrow function.

let add = (a, b=10) => {
    console.log (a + b);
}
add (-4, 3); // -1
add (4); // 14

In the above example, add (-4,3) gives -1 as output because it does not take the default value of b and add (4) gives 14 as output because here default value of b i.e., 10 is used since there is only one 4 arguments is passed during function call add (4).

Arrow Function as an expression

We can also use the arrow function as an expression.

// The arrow function is to check even and odd.
let num = 4;
let even_odd = (num%2==0)? () => console.log (num + ' is even.') : () => console.log (num + ' is odd.');
even_odd ();

this keyword and arrow function

this keyword in JavaScript refers to or points to the particular object it belongs to.
The value of this value depends on where it is used.
When this keyword is used alone, then it refers to a window object, which is a global object in JavaScript.

console.log ('This ' + this);

//Output
//This [object Window]

In the case of a function, this points to the window object (global object).

function fun (){
    console.log ('This ' + this);
}
fun();

//Output
//This [object Window]

There is no binding of this keyword in the arrow function.

const detail={
    name:"Anshul",
    age: 22,
myname: function (){
    console.log (this);
    console.log ("My name is", this.name);
},
    myage:() =>{
        console.log ("My age is", this.age);
    }
};

detail.myname();
detail.myage();

//Output
//{
// name: 'Anshul',
// age: 22,
// myname: [Function: myname],
// myage: [Function: myage]
//}
//My name is Anshul
//My age is undefined

Here, in the above example, when we define a regular function inside an object detail, this is referring or pointing to the owner of the object, which is detail in this case. But when we define an arrow function then this does not bind to the detail object, that’s why we are getting undefined as output when we are printing age using this keyword.

What are the differences between the Arrow Function and the Regular Function in JavaScript?

  1. The normal or regular function is defined using function keyword followed by the function name and parentheses () whereas an arrow function is defined using parentheses () followed by arrow operator (=>), there is no requirement of function keyword and function name in an arrow function.
    // ES5
    function mg(){
        console.log (‘Not in a single line');
    }
    mg();
    
    // ES6
    const mg = () => { console.log ("In a single line!") }
    mg();
    
  2. The normal function has an explicit return in the case of a single statement which means you have to write the return keyword when the function is returning some value.
    An arrow function has an implicit return in the case of a single statement which means that you don’t have to write the return keyword when the function is returning some value.

    function add (a,b) {
        return a+b;
    }
    const add = (a,b) => a + b;
    
  3. Curly braces ({}) are mandatory in a regular function whereas it is not mandatory in an arrow function but the function definition or body must be a single line statement or expression.
    // regular function
    function greeting() {
        console.log("Good, Morning");
    }
    greeting();
    
    // arrow function
    const greeting = () => console.log("Good, Morning");
    greeting();
    
  4. Hoisting doesn’t work in the case of function expression & arrow function but it works in normal or regular function.
    multiply(4,5);
    // regular function
    function multiply (a, b) {
        console.log ('Multiplication of '+a+' & '+b+' is '+(a*b));
    }
    //Output
    //Multiplication of 4 & 5 is 20.
    

    Here, in the above example, the function multiply() is a regular function & is called before the function is defined.

    multiply(4,5);
    // arrow function
    const multiply = (a,b) =>
    {
        console.log ('Multiplication of '+a+' & '+b+' is '+(a*b));
    }
    

    Here, in the above example, the function multiply () is defined using an arrow function & is called before the function is defined but we will be getting an error: ReferenceError: Cannot access ‘multiply()’ before initialization.

  5. There is no argument binding in the arrow function which means that we cannot access arguments passed to a function that can be accessed using the arguments object. But we can access arguments to a regular function using the arguments keyword.
    // regular function
    function sum () {
        console.log(arguments);
    }
    sum(1,8,3,5);
    
    //Output
    //[Arguments] { '0': 1, '1': 8, '2': 3, '3': 5 }
    
    // arrow function
    let sum = () => {
        console.log(arguments);
    }
    
    sum(1,8,3,5);
    

    Here, in the above example, we will get an error: Uncaught ReferenceError: arguments are not defined.

So, using the arrow function we can write a concise function which means that we can define a function in just one or a few lines of statements.

I hope you have liked this module and got to know about the arrow functions in JavaScript. It might not be easy for you to understand all the things at once. So, for this keep practicing and keep coding. For getting more modules like these, stay in contact with us.