JavaScript

coding learning websites codepractice

JS Basics

JS Variables & Operators

JS Data Types & Conversion

JS Numbers & Math

JS Strings

JS Dates

JS Arrays

JS Control Flow

JS Loops & Iteration

JS Functions

JS Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

Function Apply


In JavaScript, the apply() method allows you to call a function with a specific value of this and arguments provided as an array. This makes it a powerful tool for controlling the context in which a function runs, especially when working with functions that accept multiple or dynamic arguments. Understanding apply() helps write flexible, reusable, and context-aware code.

Why apply() Is Important

The apply() method is important because it:

  • Lets you execute a function with a specific this value.

  • Passes arguments as an array, which is useful when the number of arguments is dynamic.

  • Enables reusing functions across different objects.

  • Works with built-in functions like Math.max and Math.min that do not accept arrays directly.

  • Supports advanced techniques like method borrowing and dynamic function invocation.

Without apply(), handling variable arguments or custom contexts can be cumbersome and repetitive.

Syntax

The syntax of apply() is:

func.apply(thisArg, [argsArray])
  • func is the function to invoke.

  • thisArg is the object to use as this inside the function.

  • [argsArray] is an array of arguments to pass to the function.

Basic Example

function greet(city, country) {
  console.log(this.name + " says hello from " + city + ", " + country);
}

const student = { name: "Aarushi" };

greet.apply(student, ["Patna", "India"]);

Output:

Aarushi says hello from Patna, India

Here, this inside greet refers to the student object, and the arguments are passed as an array.

Using apply() with Arrays

apply() is particularly useful when a function expects separate arguments but you have them in an array:

const numbers = [5, 10, 15, 20];

const max = Math.max.apply(null, numbers);
const min = Math.min.apply(null, numbers);

console.log("Maximum:", max);
console.log("Minimum:", min);

Output:

Maximum: 20
Minimum: 5

This allows you to pass array elements as individual arguments to functions that don’t accept arrays directly.

Borrowing Methods with apply()

You can borrow a function from one object and use it for another using apply():

const person1 = { name: "Priya", age: 20 };
const person2 = { name: "Isha", age: 25 };

function introduce(city, hobby) {
  console.log(this.name + " is " + this.age + " years old, lives in " + city + " and enjoys " + hobby);
}

introduce.apply(person1, ["Patna", "painting"]);
introduce.apply(person2, ["Bangalore", "reading"]);

Output:

Priya is 20 years old, lives in Patna and enjoys painting
Isha is 25 years old, lives in Bangalore and enjoys reading

Method borrowing lets you reuse a function across different objects without rewriting it.

Difference Between apply() and call()

  • call() passes arguments individually: func.call(thisArg, arg1, arg2, ...).

  • apply() passes arguments as an array: func.apply(thisArg, [arg1, arg2, ...]).

Both methods set the value of this, but apply() is more convenient when working with arrays.

Common Mistakes

  • Forgetting to pass an array as the second argument in apply().

  • Passing null or undefined as thisArg without understanding the effect.

  • Confusing apply() with call() and passing arguments incorrectly.

  • Using apply() with arrow functions, which do not have their own this.

  • Passing an empty array when arguments are required.

Best Practices

  • Use apply() when the number of arguments is dynamic or stored in an array.

  • Ensure thisArg points to the correct object context.

  • Prefer call() when passing a known fixed set of arguments individually.

  • Consider modern alternatives like the spread operator (...) for simpler syntax: Math.max(...numbers).

Real-World Applications

  • Finding the maximum or minimum in an array of numbers.

  • Borrowing methods from one object and applying them to another.

  • Calling functions with dynamic argument lists.

  • Managing this context in object-oriented or functional programming.

  • Simplifying dynamic function calls in utility libraries.

Summary of Function Apply

The apply() method allows you to call a function with a specific this context and arguments as an array. It is particularly useful for method borrowing, dynamic argument lists, and functions like Math.max that do not accept arrays. Using apply() effectively makes your code more flexible, reusable, and maintainable. Understanding how apply() differs from call() and when to use the spread operator enhances your ability to handle context and arguments efficiently in JavaScript.


Practice Questions

Q1. Create a function showInfo that logs this.name, this.age. Use apply() to invoke it with { name: "Ravi", age: 28 }.

Q2. Write a function sum(a, b) and call it using apply() with [4, 6] as arguments and a dummy this object.

Q3. Create an object student with name: "Anu" and use a standalone printName() function with apply() to print her name.

Q4. Use apply() with Math.min to find the smallest number in [2, 8, 5, 1, 9].

Q5. Create a function introduce(city, country) and use apply() to bind it with a person object and pass array arguments.

Q6. Create a function calculateArea(length, width) and use apply() to pass [5, 3] as arguments.

Q7. Define a sayHello function and use apply() to call it with different this values like { name: "Sara" }, { name: "Tom" }.

Q8. Write a function showDetails() that logs this.id and this.role. Use apply() with { id: 101, role: "Admin" }.

Q9. Create a function multiply(a, b, c) and call it using apply() with array [2, 3, 4]. Print the result.

Q10. Write a function concatStrings(a, b, c) and use apply() to pass ["JavaScript", "is", "fun"] and print "JavaScript is fun".


Try a Short Quiz.

coding learning websites codepractice

No quizzes available.

JavaScript

online coding class codepractice

JS Basics

JS Variables & Operators

JS Data Types & Conversion

JS Numbers & Math

JS Strings

JS Dates

JS Arrays

JS Control Flow

JS Loops & Iteration

JS Functions

JS Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

Go Back Top