Learn Simpli

Free Online Tutorial For Programmers, Contains a Solution For Question in Programming. Quizzes and Practice / Company / Test interview Questions.

What is apply in Javascript and when to use

What is apply in Javascript?

The apply method allows passing the value of this and it accepts 2 parameters.

First parameter: The value which should be bound to this

Second parameter: An array with parameters

Let’s write an example to see how apply method can be invoked

var status = 200;
var message = 'Default';
const error = {
    status: 404,
    message: 'Requested url not found'
};

const notAthourized = {
    status: 405,
    message: 'Not authorised'
};

const success = {
    status: 200,
    message: 'Welcome'
};

const response = {
    getStatus: function () {
        return {
            status: this.status,
            message: this.message
        }
    }
};

let getResponse1 = response.getStatus();
let getResponse2 = response.getStatus.apply(this);
let getResponse3 = response.getStatus.apply(error);
let getResponse4 = response.getStatus.apply(notAthourized);
let getResponse5 = response.getStatus.apply(success);

console.log(getResponse1);
console.log(getResponse2);
console.log(getResponse3);
console.log(getResponse4);
console.log(getResponse5);

// Output
// {status: undefined, message: undefined}
// {status: "200", message: "Default"}
// {status: 404, message: "Requested url not found"}
// {status: 405, message: "Not authorised"}
// {status: 200, message: "Welcome"}

For beginners in the Javascript:

For understanding how apply method works properly in Javascript, its necessary to understand how this keyword works with object methods. Consider the below example,

The below code works perfectly

let Person = {
    firstName: "Sundar",
    lastName: "Pichai",
    getFllName() {
        console.log(`Hello, ${this.firstName} ${this.lastName}!`);
    }
};

Person.getFllName();
// Output
// Hello, Sundar Pichai!

Now split get full name function into different function and create multiple person objects, and the below code doesn’t work properly

var Person = {
    fullName: function() {
        console.log(`Hello, ${this.firstName} ${this.lastName}!`);
    }
}

var Person1 = {
    firstName: "Sundar",
    lastName: "Pichai",
}
var Person2 = {
    firstName: "Rajni",
    lastName: "Kant",
}
var x = Person.fullName(Person1); 
// Output
// Hello, undefined undefined!

To resolve the above problem apply method helps. That means you can now assign a different object when calling an existing function. Consider the below-modified code.

var Person = {
    fullName: function() {
        console.log(`Hello, ${this.firstName} ${this.lastName}!`);
    }
}

var Person1 = {
    firstName: "Sundar",
    lastName: "Pichai",
}

var Person2 = {
    firstName: "Rajni",
    lastName: "Kant",
}

Person.fullName.apply(Person1); 
Person.fullName.apply(Person2); 
// Output
// Hello, Sundar Pichai!
// Hello, Rajni Kant!

What is apply in Javascript?
Apply methods help in writing different methods and that can be used on different objects by specifying the object name with the help of apply key. Even apply method helps you to use the inbuilt methods of Javascript in a different way, consider a below example

// Find the largest number 
console.log(Math.max(1,2,3));
// output
// 3

 

Now assume that you want to pass an array and return the max number

// Find the largest number by passing an array
console.log(Math.max([0, 1, 2]));
// output
// NaN

 

To resolve the above problem you can use the apply method.

// Find the largest number 
console.log(Math.max.apply(null, [1,2,3]));
// output
// 3

Also, read What is Bind?

3 thoughts on “What is apply in Javascript and when to use

Comments are closed.