Skip to content
Advertisements

JavaScript Arrow functions

Why arrow.functions ?

The arrow functions introduced in ES6 provide a short way to write functions in JavaScript. Arrow functions are defined as static. This function does not depend on how other functions are called. It only depends on the surrounding content.
Arrow functions javascirpte is one of the most used functions (you can see how popular it is below this article). This function description is particularly suitable for non-method functions.


A normal function is defined in this way:

        let normalFunction = function () {
            // ..................
        }

The arrow function is defined as:

        let arrowFunction = () => { /*.............*/ }

There are different ways of using the arrow function. ( you can learn by examining the following examples )


Arrow functions usage of

There are two important features of arrow functions. Short-handed use and not including this context.

Short functions:

        let names = [ "john", "alice", "rick", "bob", "oliver"]

        let arr = names.map(function (x) {
            return names.indexOf(x);
        })

        console.log(arr)

If we want to write this function as an arrow functions, we have to do the following:

        let names = [ "john", "alice", "rick", "bob", "oliver"]

        let arr = names.map((x) => { return names.indexOf(x)});

        console.log(arr)

Examine the above two samples. As you can see, thanks to the arrow function, codes can be written shorter.

The “this” value is not used in the arrow functions.


How work the “this” value in arrow functions?

The arrow functions are similar to normal functions. It is not the same. So there are differences between them. One of these is “this” value. In a normal function, the value “this” is used.

        let myFunction = function(name,surname){
            this.name = name;
            this.surname = surname;
        }

When we apply this to the arrow function, we reach the value “undefined”. So why?

The this scope with arrow functions is inherited from the execution context. An arrow function does not bind this at all, so its value will be looked up in the call stack, so in this code myFunction.name() or myFunction.surname() will not work, and will return the string “undefined undefined”:

        let myFunction = {
            name: "john",
            surname: "allen",
            fullname: () => {
                return name + " " + surname
            }
        }

        // Try and  you see the result

        //let myFunction = {
        //    name: "john",
        //    surname: "allen",
        //    fullname: () => {
        //        return this.name + " " + this.surname
        //    }
        //}

Due to this, arrow functions are not suited as object methods.

Arrow functions cannot be used as constructors either, when instantiating an object will raise a TypeError.

This is where regular functions should be used instead, when dynamic context is not needed.

This is also a problem when handling events. DOM Event listeners set this to be the target element, and if you rely on this in an event handler, a regular function is necessary:

        let click = document.querySelector("#click");
        click.addEventListener("click", () => {
            // .............
        })
        let click = document.querySelector("#click");
        click.addEventListener("click", function () {
            // .................
        })

Arrow function – strict mode

This value from the inclusive lexical context is ignored when strict mode rules are applied

    let stringFunction = () => { "use strict"; return this };
    stringFunction() === window

bind, call and apply

Since the arrow functions do not have “this” value, the call (), apply (), and bind () methods are different in the way they are used. Let us examine these usage patterns respectively.

call() and apply():

call() and apply() perform a task similar to bind by explicitly specifying what value this should store inside a function.
However, one major difference between them and bind() is that call() and apply() immediately calls the function, as opposed to simply preparing a copy of the function with a bound this value for future use.

The first argument in both cases is the value of this that we wish for the called function to have.

Essentially, the only difference between these two methods is the fact that in apply , the second argument is an array object of arguments while in call, all arguments are sent in a comma separated format.

For example:

        let cat = { name: "cat" };
        let dog = { name: "dog" };

        function animals(x) {
            return (this.name + " is " + x);
        }

        console.log(animals.call(cat, "alice"));
        console.log(animals.apply(dog, ["alex"]));

output:

[object Object] cat is alice
[object Object] dog is alex

Note: Both call() and apply() are methods that are available on the prototype of the default Function object.

bind()

bind() allows us to explicitly define what value this will have inside a function by binding an object to that function.
The bound object serves as the context(this value) for the function that it was bound to.
To use it, we need primarily two things – An object to bind to a function and a function that this object is to be bound to.

The first argument used inside the bind() directive serves as the this value and the arguments that follow it are optional and serve as the arguments for the bound function.

let fruit = function(person, color) { 
        this.person = person; 
        this.color = color; 
        this.displayInfo = function() { 
            document.write(this.person + " is " + this.color + '<br>'); 
        } 
    } 
  
let bindingObj = { 
        person : "Banana", 
        color : "Yellow", 
      } 
  
let fruit1 
    = new fruit("Orange", "orange"); 
  
fruit1.displayInfo(); 

let newBound = fruit1.displayInfo.bind(bindingObj); 
  
newBound(); 

output:

Orange is orange
Banana is Yellow


JavaScript Arrow Function Examples

Example 1

        let sum = (x, y) => x + y;
        console.log(sum(6, 5));
        console.log(sum(7, 8));

output:

11
15


Example 2

        let example = x => {
            if (x > 10)
                return 10;
            return x;
        }

        console.log(example(16));
        console.log(example(8));

output:

10
8


Example 3

        let example = x => ({ x: x })

        console.log(example(3));
        console.log(example(3).x);

output:

{x: 3}
3


Example 4

        let list = [3, 5, 8, 2, 1, 6, 9, 4];

        console.log(list.sort((a, b) => b - a));

output:

[9, 8, 6, 5, 4, 3, 2, 1]


Example 5

        let animals = ["cat", "dog", "horse", "donkey", "rabbit"];
        console.log(animals.map(x => x.length));

output:

[ cat , dog , horse , donkey , rabbit ]


Example 6

        let arr = () => ({
            first: "john",
            second: "rick",
            third: "alex"
        });

        console.log(arr())

output:

{first: “john”, second: “rick”, third: “alex”}


Note:

        () => 25;     // no parameters
        x => 25;      // single parameter
        (x, y) => 25; // multiple parameters

Example 7

        let number = x => x > 10 ? 10 : x;

        let arr1 = number(20);
        let arr2 = number(15);
        let arr3 = number(5);

        console.log(arr1);
        console.log(arr2);
        console.log(arr3);

output:

10
10
5


Arrow functions
Arrow functions

Browser Support

Chrome45
Edgeyes
Firefox22
Internet Explorerno
Opera32
Safari10
Android webview45
Chrome for Android45
Edge mobileyes
Firefox for Android22
Opera Android32
Advertisements

2 Comments »

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: