Back to Web Development
2026-02-055 min read

Function Apply (Web Development)

Learn Function Apply (Web Development) step by step with clear examples and exercises.

Why This Matters

Understanding and utilizing JavaScript's Function.prototype.apply() method is essential for enhancing your problem-solving skills, optimizing code, and handling complex scenarios more efficiently in web development. This method enables you to call a function with a specified this value and an array of arguments, making it an indispensable tool in the web developer's arsenal.

By mastering Function.prototype.apply(), you will be able to:

  • Simplify code by providing an alternative way to pass arguments to functions
  • Dynamically change the this context within a function call
  • Improve code readability and maintainability by separating concerns between objects and their methods

Prerequisites

To fully grasp this lesson, you should have a solid understanding of the following concepts:

  1. JavaScript basics (variables, data types, operators)
  2. Functions in JavaScript
  3. Objects and their properties in JavaScript
  4. Callbacks and higher-order functions
  5. Understanding the this keyword and its behavior in JavaScript
  6. Familiarity with ES6 syntax and arrow functions (optional but recommended)

Core Concept

The Function.prototype.apply() method allows you to call a function with a specified this value and an array of arguments. It takes two arguments:

  1. The object to be used as the new this context within the function. If omitted, the global object (i.e., window in browsers) is used.
  2. An array-like object (usually an array) that represents the arguments to be passed to the function.

Here's a simple example demonstrating how to use Function.prototype.apply():

function greet(name, location) {
console.log(`Hello, ${name} from ${location}`);
}

const user = { name: 'John', location: 'New York' };
greet.apply(user, ['Sarah']); // Outputs: Hello, Sarah from New York

In this example, the greet() function is called using the apply() method with user as the new this context and an array containing a single argument, 'Sarah'. The output shows that the name property of the user object (which has the value 'John') is overridden within the greet() function by the provided argument ('Sarah').

Calling a Function with a Default Context

When you don't provide an explicit this context, the global object (i.e., window in browsers) is used as the default context:

function greet() {
console.log(`Hello from ${this.location}`);
}

const user = { location: 'New York' };
greet.apply(); // Outputs: Hello from global (window in browsers)
greet.call(user); // Outputs: Hello from New York

In this example, the greet() function logs the value of this.location. When called with apply(), it uses the global object as its context and outputs 'Hello from global (window in browsers)'. However, when using Function.prototype.call() with a user object as the new context, it correctly outputs 'Hello from New York'.

Worked Example

Let's consider a more complex example where we have an object representing a user and a method to calculate the total score based on some criteria. We can use Function.prototype.apply() to call this method with different users:

const user1 = {
name: 'John',
level: 5,
points: 200,
};

const user2 = {
name: 'Sarah',
level: 3,
points: 150,
};

function calculateScore(user) {
const baseScore = user.points * user.level;
const extraScore = user.level > 4 ? 50 : 0;
console.log(`${user.name}'s total score is ${baseScore + extraScore}`);
}

calculateScore(user1); // Outputs: John's total score is 1000
calculateScore.apply(user2); // Outputs: Sarah's total score is 650

In this example, we first define two user objects, user1 and user2. We then create a function called calculateScore(), which calculates the user's total score based on their points and level. By default, when we call calculateScore(user1), it uses the global object as the this context, and the correct output is generated for user1. However, if we want to calculate Sarah's score using the same function but with user2 as the this context, we can use Function.prototype.apply() to achieve this.

Common Mistakes

1. Forgetting the array argument

When using Function.prototype.apply(), it is essential to pass an array-like object as the second argument. If you forget to do so, you may encounter errors due to incorrect or missing arguments being passed to the function:

function greet(name) {
console.log(`Hello, ${name}`);
}

const user = { name: 'John' };
greet.apply(user); // Error: Uncaught TypeError: greet() requires 1 argument

In this example, the greet() function expects one argument, but we forgot to pass an array containing the argument when using Function.prototype.apply(). To fix this issue, we should pass an array with a single element:

const user = { name: 'John' };
greet.apply(user, ['Sarah']); // Outputs: Hello, Sarah

2. Not considering the new this context

When using Function.prototype.apply(), it is crucial to consider that the function will be called with a different this value than when called without apply(). This can lead to unexpected behavior if you are not aware of this change:

const user = { name: 'John' };

function greet() {
console.log(this.name);
}

greet(); // Outputs: undefined (global object `window` in browsers)
greet.apply(user); // Outputs: John

In this example, the greet() function logs the value of this.name. When called without apply(), it uses the global object as its context and outputs undefined. However, when using Function.prototype.apply() with a user object as the new context, it correctly outputs 'John'.

Practice Questions

  1. Write a function sumArray() that takes an array of numbers as input and returns their sum. Use Function.prototype.apply() to call this function with different arrays.
  2. Given the following user object:
const user = {
name: 'John',
level: 5,
points: 200,
calculateTotalScore: function () {
const baseScore = this.points * this.level;
const extraScore = this.level > 4 ? 50 : 0;
console.log(`${this.name}'s total score is ${baseScore + extraScore}`);
},
};

Call the calculateTotalScore() method using Function.prototype.apply() with a different user object having a higher level and more points:

const newUser = {
name: 'Sarah',
level: 6,
points: 300,
};

FAQ

How does Function.prototype.apply() differ from Function.prototype.call()?

Both Function.prototype.apply() and Function.prototype.call() allow you to call a function with a specified this value, but they have subtle differences:

  • Function.prototype.apply() takes an array-like object as its second argument, while Function.prototype.call() expects comma-separated arguments.
  • Function.prototype.apply() can be more efficient when dealing with large arrays of arguments since it doesn't need to create an arguments object.

Can I use Function.prototype.apply() with ES6 arrow functions?

No, you cannot use Function.prototype.apply() with ES6 arrow functions because they do not have a separate this value like traditional function declarations or expressions. Instead, use the call() method with arrow functions:

const greet = (name) => console.log(`Hello, ${name}`);

const user = { name: 'John' };
greet.call(user, 'Sarah'); // Outputs: Hello, Sarah
Function Apply (Web Development) | Web Development | XQA Learn