Learnitweb

JavaScript apply() method

1. Introduction

The apply() method calls a function. While calling this method you can provide this argument and arguments as an array.

The apply() method is identical to that of call() with difference that arguments are passed to call() as separate arguments whereas arguments are passed to apply() as an array.

Following are valid versions of apply():

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
apply(thisArgument)
apply(thisArgument, argsArray)
apply(thisArgument) apply(thisArgument, argsArray)
apply(thisArgument)
apply(thisArgument, argsArray)

Here, thisArgument is the value of this provided while calling the function. The argsArray is the optional array of arguments.

2. Examples of call()

Example 1: Using apply() to call a function

In this example, we are using apply() without any argument.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
function hello() {
console.log("hello world");
}
hello.apply(); //hello world
function hello() { console.log("hello world"); } hello.apply(); //hello world
function hello() {
  console.log("hello world");
}
hello.apply(); //hello world

Example 2: Using apply() with this

In this example, while using apply(), we are passing one argument. Since the first argument is this, it will refer to { msg: "hello world" }.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
function hello() {
console.log(this.msg);
}
hello.apply({ msg: "hello world" }); // hello world
function hello() { console.log(this.msg); } hello.apply({ msg: "hello world" }); // hello world
function hello() {
  console.log(this.msg);
}
hello.apply({ msg: "hello world" }); // hello world

Example 3: Using call() with built-in functions

The apply() method can be used with some built-in functions where array can be passed as argument. Following is one example:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
const numbers = [1, 5, 9, 10];
let max = Math.max.apply(null, numbers);
console.log(max); // 7
const numbers = [1, 5, 9, 10]; let max = Math.max.apply(null, numbers); console.log(max); // 7
const numbers = [1, 5, 9, 10];

let max = Math.max.apply(null, numbers);
console.log(max);  // 7

3. Conclusion

In this tutorial, we discussed apply() method. This method is identical to call() except that it accepts arguments as array. We recommend to read our previous tutorial about call().