in , ,

JavaScript Arrow Function

JavaScript Arrow Function
JavaScript Arrow Function

In this tutorial, you will learn about the JavaScript arrow function with the assistance of examples.

Introduction

In the event that you are a JavaScript developer, you may realize that JavaScript conforms to the ECMAScript (ES) standards. The ES6, or ECMAScript 2015 determinations, had presented a portion of the progressive details for JavaScript, similar to Arrow Functions, Classes, Rest and Spread operators, Promises, let and const, and so on

An arrow function is one of the highlights presented in the ES6 adaptation of JavaScript. It allows you to make functions in a cleaner way contrasted with regular functions. For instance,

This function

// function expression
let x = function(x, y) {
   return x * y;
}

can be written as

// using arrow functions
let x = (x, y) => x * y;

using an arrow function.


Arrow Function Syntax

The syntax of the arrow function is:

let myFunction = (arg1, arg2, ...argN) => {
    statement(s)
}

Here,

  • myFunction is the name of the function
  • arg1, arg2, …argN are the function arguments
  • statement(s) is the function body

If the body has a single statement or expression, you can write the arrow function as:

let myFunction = (arg1, arg2, ...argN) => expression

Example 1: Arrow Function with No Argument

In the event that a function doesn’t take any contention, at that point you should use empty parentheses. For instance,

let greet = () => console.log('Hello');
greet(); // Hello

Example 2: Arrow Function with One Argument

In the event that a function has just a single argument, you can discard the parentheses. For instance,

let greet = x => console.log(x);
greet('Hello'); // Hello 

Example 3: Arrow Function as an Expression

You can also dynamically create a function and use it as an expression. For example,

let age = 5;

let welcome = (age < 18) ?
  () => console.log('Baby') :
  () => console.log('Adult');

welcome(); // Baby

Model 4: Multiline Arrow Functions

In the event that a function body has different proclamations, you need to put them inside curly brackets {}. For instance,

let sum = (a, b) => {
    let result = a + b;
    return result;
}

let result1 = sum(5,7);
console.log(result1); // 12

this with Arrow Function

Inside a regular function, this keyword refers to the function where it is called.

In any case, this isn’t associated with arrow works. Arrow work doesn’t have its own this. So at whatever point you call this, it refers to its parent scope. For instance,

Inside a regular function

function Person() {
    this.name = 'Salman',
    this.age = 25,
    this.sayName = function () {

        // this is accessible
        console.log(this.age);

        function innerFunc() {

            // this refers to the global object
            console.log(this.age);
            console.log(this);
        }

        innerFunc();

    }
}

let x = new Person();
x.sayName();

Output

25
undefined
Window {}

Here, this.age inside this.sayName() is available on the grounds that this.sayName() is the strategy for an object.

Nonetheless, innerFunc() is an ordinary function and this.age isn’t available on the grounds that this alludes to the global object (window object in the browser). Consequently, this.age inside the innerFunc() function gives undefined.

Inside an arrow function

function Person() {
    this.name = 'Salman',
    this.age = 25,
    this.sayName = function () {

        console.log(this.age);
        let innerFunc = () => {
            console.log(this.age);
        }

        innerFunc();
    }
}

const x = new Person();
x.sayName();

Output

25
25

Here, the innerFunc() work is characterized using the arrow function. Furthermore, inside the arrow function, this alludes to the parent’s scope. Henceforth, this. age gives 25.


Arguments Binding

Regular functions have arguments binding. That is the reason when you pass arguments to a regular function, you can get to them using the arguments watchword. For instance,

let x = function () {
    console.log(arguments);
}
x(4,6,7); // Arguments [4, 6, 7]

Arrow works don’t have arguments binding.

At the point when you attempt to get to an argument using the arrow work, it will give an error. For instance,

let x = () => {
    console.log(arguments);
}

x(4,6,7); 
// ReferenceError: Can't find variable: arguments

To solve this issue, you can use the spread syntax. For example,

let x = (...n) => {
    console.log(n);
}

x(4,6,7); // [4, 6, 7]

Arrow Function with Promises and Callbacks

Arrow functions provide better syntax to write promises and callbacks. For example,

// ES5
asyncFunction().then(function() {
    return asyncFunction1();
}).then(function() {
    return asyncFunction2();
}).then(function() {
    finish;
});

can be written as

// ES6
asyncFunction()
.then(() => asyncFunction1())
.then(() => asyncFunction2())
.then(() => finish);

Things You Should Avoid With Arrow Functions

  1. You ought not use arrow functions to make techniques inside objects.
let person = {
    name: 'Salman',
    age: 25,
    sayName: () => {

        // this refers to the global .....
        //
        console.log(this.age);
    }
}

person.sayName(); // undefined

2. You cannot use an arrow function as a constructor. For example,

let Foo = () => {};
let foo = new Foo(); // TypeError: Foo is not a constructor

Note: Arrow functions were introduced in ES6. Some browsers may not support the use of arrow functions. Visit JavaScript Arrow Function support to learn more.


Thanks for reading! We hope you found this tutorial helpful and we would love to hear your feedback in the Comments section below. And show us what you’ve learned by sharing your photos and creative projects with us.

salman khan

Written by worldofitech

Leave a Reply

Difference Between Guided and Unguided Media

Difference Between Guided and Unguided Media

JavaScript Default Parameters

JavaScript Default Parameters