-
Hajipur, Bihar, 844101
Hajipur, Bihar, 844101
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 Functions
Function Definitions
Function Parameters
Function Invocation
Function Call
Function Apply
Function Bind
Function Closures
JS Arrow Function
JS Objects
JS Objects
JS Object Properties
JS Object Methods
JS Object Display
JS Object Constructors
Object Definitions
Object Get / Set
Object Prototypes
Object Protection
JS Classes & Modules
JS Async Programming
JS Advanced
JS Destructuring
JS Bitwise
JS RegExp
JS Precedence
JS Errors
JS Scope
JS Hoisting
JS Strict Mode
JS this Keyword
JS HTML DOM
DOM Intro
DOM Methods
DOM Document
DOM Elements
DOM HTML
DOM Forms
DOM CSS
DOM Animations
DOM Events
DOM Event Listener
DOM Navigation
DOM Nodes
DOM Collections
DOM Node Lists
JS BOM (Browser Object Model)
JS Web APIs
Web API Intro
Web Validation API
Web History API
Web Storage API
Web Worker API
Web Fetch API
Web Geolocation API
JS AJAX
AJAX Intro
AJAX XMLHttp
AJAX Request
AJAX Response
AJAX XML File
AJAX PHP
AJAX ASP
AJAX Database
AJAX Applications
AJAX Examples
JS JSON
JSON Intro
JSON Syntax
JSON vs XML
JSON Data Types
JSON Parse
JSON Stringify
JSON Objects
JSON Arrays
JSON Server
JSON PHP
JSON HTML
JSON JSONP
JS Graphics & Charts
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.
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.
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.
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.
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.
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.
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.
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.
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).
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.
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.
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".
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 Functions
Function Definitions
Function Parameters
Function Invocation
Function Call
Function Apply
Function Bind
Function Closures
JS Arrow Function
JS Objects
JS Objects
JS Object Properties
JS Object Methods
JS Object Display
JS Object Constructors
Object Definitions
Object Get / Set
Object Prototypes
Object Protection
JS Classes & Modules
JS Async Programming
JS Advanced
JS Destructuring
JS Bitwise
JS RegExp
JS Precedence
JS Errors
JS Scope
JS Hoisting
JS Strict Mode
JS this Keyword
JS HTML DOM
DOM Intro
DOM Methods
DOM Document
DOM Elements
DOM HTML
DOM Forms
DOM CSS
DOM Animations
DOM Events
DOM Event Listener
DOM Navigation
DOM Nodes
DOM Collections
DOM Node Lists
JS BOM (Browser Object Model)
JS Web APIs
Web API Intro
Web Validation API
Web History API
Web Storage API
Web Worker API
Web Fetch API
Web Geolocation API
JS AJAX
AJAX Intro
AJAX XMLHttp
AJAX Request
AJAX Response
AJAX XML File
AJAX PHP
AJAX ASP
AJAX Database
AJAX Applications
AJAX Examples
JS JSON
JSON Intro
JSON Syntax
JSON vs XML
JSON Data Types
JSON Parse
JSON Stringify
JSON Objects
JSON Arrays
JSON Server
JSON PHP
JSON HTML
JSON JSONP
JS Graphics & Charts
