JavaScript

JavaScript Apply() Method

apply() is a predefined JavaScript method that can be used to invoke a function with arguments provided as an array and a given “this” value. The functionality of the JavaScript apply() method and the call() method is the same, except the apply() method passes a single array of arguments rather than individual arguments. You can also utilize the JavaScript apply() method to borrow another object’s method and to append the array elements.

This write-up will discuss the JavaScript apply() method. Moreover, we will also demonstrate the usage of the JavaScript apply() method for function borrowing and appending elements of one array to another with the help of examples. So, let’s start!

JavaScript apply() Method

The JavaScript “apply()” method permits you to invoke a function while passing an “array” as an argument and a given “this” value. To utilize the “Function.prototype.apply()” method, you have to follow its syntax:

function.apply(thisArg, [args]);

You can see that the JavaScript “apply()” method has two parameters. The first parameter is “thisArg” which denotes the “this” value provided to call the “function”. The next parameter is an array “[args]” which represents the parameters of the “function”. For “args,” an array or array-like object can be passed as an argument.

Now, you may be assuming that isn’t JavaScript apply() and call() method are same? The answer is yes. Both methods are similar in functionality; however, instead of individual arguments, the apply() method accepts the function arguments as an array.

Example: Using JavaScript apply() method

To show you how JavaScript apply() method works, firstly, we will create an “employee” object which will have two properties firstName and the lastName:

const employee = {
    firstName: 'Jack',
    lastName: 'Smith'
}

In the next step, we will create a “welcome()” function that accepts two parameters: greeting and message. In the body of the “welcome()” function, we referred to the “employee” object using “this”, which has the firstName and lastName properties:

function welcome(greeting, message) {
    return `${greeting} ${this.firstName} ${this.lastName}. ${message}`;
}

Now, we will utilize the JavaScript apply() method with the welcome() function by passing the “employee” as an object, ‘Hi’ as a greeting argument, and ‘Hope you are fine’ as a message argument. Here, the arguments of the “welcome()” function are passed as an array to the “apply()” method:

let text = welcome.apply(employee, ['Hi', 'Hope you are fine']);
console.log(text);

Upon executing the above-given example, you will see the following output:

In case of using the call() method, you have to pass all the required arguments separately:

let text = welcome.call(employee, 'Hi', 'Hope you are fine');
console.log(text);

Function Borrowing using JavaScript apply() method

You can also use the apply() method to borrow another object’s method without duplicating the code.

Example: Function Borrowing using JavaScript apply() method

To explain the function borrowing, the first thing we need to do is create two objects and define some function for each of them. For this purpose, we will create our first object named “system”. The “system” object will have two properties: “name” and “active”. Next, we will define two methods, “turnOn()” and “turnOff(),” which will be associated with the “active” property:

const system = {
    name: 'HP Laptop',
    active: false,
    turnOn() {
        this.active = true;
        return `The ${this.name} is active`;
    },
    turnOff() {
        this.active = false;
        return `The ${this.name} is inactive`;
    }
};

After doing so, we will create another object, “client” which contain a “name” and “active” property:

const client= {
    name: 'HP Chromebook',
    active: false
};

Note that we have not added turnOn() and turnOff() methods for the client object. Now, to use the turnOn() method of the “system” object for the “client” object, we can use the “apply()” method for borrowing the specified method:

let message = system.turnOn.apply(client);
console.log(message);

Have a look at the complete code of the provided example and its output:

Appending an array to another using JavaScript apply() method

The JavaScript apply() method also offers you the facility to append elements of one array to another.

Example: Appending an array to another using JavaScript apply() method

First of all, we will create two arrays, “array1” and “array2,” having their respective values:

let array1 = [10, 20, 30];
let array2 = [70, 80, 90];

We want to append the elements of array2 “70”, “80”, and “90” to array 1. To do so, we will execute the following code:

array1.push.apply(array1, array2);
console.log(array1);

As you can see from the output, we have successfully appended the elements of array2 to array1:

Conclusion

In JavaScript, apply() is a built-in method that can invoke a function with arguments provided as an array and a given this value. You can also utilize the JavaScript apply() method for using a method that belongs to another object. This write-up discussed the JavaScript apply() method. Moreover, we have also demonstrated the usage of the JavaScript apply() method for function borrowing and appending elements of one array to another with the help of examples.

About the author

Sharqa Hameed

I am a Linux enthusiast, I love to read Every Linux blog on the internet. I hold masters degree in computer science and am passionate about learning and teaching.