JavaScript Notes
Master JavaScript apply() method with syntax, this binding, array arguments, function borrowing, real-world use cases, common mistakes, and interview Q&A.
What is apply()?
apply() is a built-in method available on every JavaScript function. It lets you call a function immediately while manually choosing what this should be inside it — and you pass all the arguments as a single array (or array-like object).
Think of it as calling a function and saying: *"Run this function, but pretend this is the object I give you, and here are all the arguments bundled in an array."*
Why Does apply() Exist?
JavaScript functions are objects. They inherit helper methods from Function.prototype:
call()— call with individual argumentsapply()— call with an array of argumentsbind()— return a new function for later
apply() solves this classic problem:
60
Syntax
functionName.apply(thisArg, argsArray);Parameters
| Parameter | Required | Description |
|---|---|---|
thisArg | Yes | The value that becomes this inside the function. Pass null or undefined if this doesn't matter. |
argsArray | No | An array (or array-like object) whose elements become the function's arguments. Pass null to call with no arguments. |
Return Value
apply() returns whatever the called function returns — just like a normal call.
42
How apply() Works Internally
Internally, apply(thisArg, [a, b]) behaves exactly like call(thisArg, a, b) — the engine unpacks the array into positional arguments.
Basic Example — Step by Step
Riya from Patna works as a Frontend Developer
Step-by-step execution trace:
Multiple Examples
Example 1 — apply() with Math.max()
95
Math.max() needs separate values: Math.max(88, 91, 76, 95, 84). apply() unpacks the array into those separate values. Modern alternative:
console.log(Math.max(...marks)); // Same result using spread95
Example 2 — Function Borrowing
Aman teaches JavaScript
student doesn't have an introduce method, but it borrows one from teacher. apply() sets this to student so this.name reads "Aman".
Example 3 — Converting arguments to Array
function showArguments() {
const values = Array.prototype.slice.apply(arguments);
console.log(values);
}
showArguments("HTML", "CSS", "JavaScript");["HTML", "CSS", "JavaScript"]
arguments is array-like but not a real array. Array.prototype.slice.apply(arguments) borrows slice and runs it with this = arguments, converting it to a real array.
Example 4 — Dynamic Constructor Arguments
Priya 25 Mumbai
Scope Chain Visualization
Comparison Table — call() vs apply() vs bind()
| Feature | call() | apply() | bind() |
|---|---|---|---|
| Executes immediately | ✅ Yes | ✅ Yes | ❌ No |
| Argument format | Comma-separated | Array / array-like | Comma-separated |
| Returns | Function result | Function result | New bound function |
Changes this permanently | ❌ No | ❌ No | ✅ Yes (new fn) |
| Works on arrow functions | ❌ No | ❌ No | ❌ No |
| Best for | Single call, separate args | Single call, array args | Reusable bound function |
Common Mistakes
❌ Mistake 1 — Passing Arguments Separately
function add(a, b) { return a + b; }
// WRONG — second param must be array-like
console.log(add.apply(null, 10, 20));TypeError: CreateListFromArrayLike called on non-object
30
❌ Mistake 2 — Thinking apply() Permanently Changes this
function showName() { return this.name; }
const user = { name: "Ravi" };
console.log(showName.apply(user)); // ✅ works
console.log(showName()); // ❌ this is global/undefinedRavi undefined
apply() is temporary — this reverts after the call.
❌ Mistake 3 — Using apply() on Arrow Functions
undefined
Arrow functions ignore the thisArg passed to apply(). Their this is fixed at definition time.
❌ Mistake 4 — Huge Array Overflow
Use reduce or a loop instead for very large arrays.
Edge Cases
Edge Case 1 — null argsArray
function greet() { return "Hello!"; }
console.log(greet.apply(null, null));Hello!
Passing null as argsArray is valid — the function gets no arguments.
Edge Case 2 — Strict Mode Difference
"use strict";
function whoIsThis() { return this; }
console.log(whoIsThis.apply(null)); // null in strict mode
console.log(whoIsThis.apply(42)); // 42 in strict mode (no boxing)null 42
In non-strict mode, null/undefined thisArg becomes the global object, and primitive values get boxed to their wrapper objects.
Real World Use Cases
| Use Case | Why apply()? |
|---|---|
Math.max()/Math.min() on array (legacy) | Needs spread — array to args |
| Function borrowing between objects | Custom this needed |
Converting arguments to real array | Borrow Array.prototype.slice |
| Dynamic function invocation frameworks | Args arrive as arrays |
| Polyfill implementations | Exact this control |
Best Practices ✅
- Prefer spread syntax (
...arr) in modern code when you only need to unpack args - Use
apply()when targeting older environments (ES5) - Use
call()when arguments are already individual values - Use
bind()when you need a reusable function for later - Never use
apply()expecting it to permanently bindthis
Interview Questions 🎯
Q1. What is the apply() method in JavaScript?
apply() is a Function.prototype method that immediately invokes a function with a specified this value and arguments provided as an array or array-like object. Unlike regular calls, it lets you control both this and pass collected argument lists.
Q2. What is the difference between call() and apply()?
The only difference is how arguments are passed:
call(thisArg, arg1, arg2)— arguments are passed individuallyapply(thisArg, [arg1, arg2])— arguments are passed as an array
Both execute the function immediately and return its result.
Q3. Does apply() permanently change this?
No. apply() changes this only for that single function call. The original function is unaffected — the next call will use its default this again. Only bind() creates a permanently bound function.
Q4. Does apply() work with arrow functions?
apply() can call an arrow function, but it cannot change the arrow function's this. Arrow functions capture this lexically (from where they are written), and no method — not call, apply, or bind — can override it.
Q5. What happens when you pass null as thisArg?
- Non-strict mode:
nullbecomes the global object (windowin browsers,globalin Node) - Strict mode:
thisinside the function will be exactlynull
Q6. Why is apply() less common in modern JavaScript?
Because the spread operator (...) handles the main use case more cleanly:
// Old way
Math.max.apply(null, numbers);
// Modern way
Math.max(...numbers);Q7. How does function borrowing with apply() work?
Function borrowing means using one object's method on another object. With apply(), you call the method directly with thisArg set to the borrowing object:
Q8. What is the difference between apply() and bind()?
apply() | bind() | |
|---|---|---|
| - | ----------- | ---------- |
| Execution | Immediate | Returns new function (deferred) |
| Returns | Function result | New bound function |
| Use case | One-time call | Reusable callback |
Key Takeaways 🔑
apply()calls a function immediately with a customthisand array-style arguments- It does not permanently change
this— the binding is per-call only - Arrow functions cannot have their
thischanged byapply() - In modern code, spread syntax (
...arr) often replacesapply()for argument spreading apply()is essential for function borrowing and working with array-like objects- Understanding
apply()builds your foundation for closures,this, and interview questions
Practice Problems
- Use
apply()to call agreetUser(greeting, punctuation)function withthisset to a student object. - Find the minimum of an array of prices using
Math.min.apply(). - Rewrite both examples using spread syntax and compare readability.
- Borrow a
fullName()method from aPersonobject and apply it on aCustomerobject. - Write a
borrowMethod(target, source, methodName, args)utility that usesapply()internally. - Explain in one sentence why
apply()cannot changethisfor arrow functions.
Summary
apply() is a Function.prototype method that immediately calls a function with a custom this value and arguments provided as an array or array-like object. It is closely related to call() (same immediate execution, different argument format) and bind() (which defers execution). The three key facts to remember: it runs immediately, it's temporary (doesn't permanently bind), and it doesn't work on arrow functions for this binding. In modern JavaScript, spread syntax covers many use cases, but apply() remains a critical concept for interviews and understanding JavaScript's core function mechanics.
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for JavaScript apply() Method - Complete Guide with Examples.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this JavaScript Master Course topic.
Search Terms
javascript-complete-guide, javascript master course, javascript, complete, guide, advanced, apply, javascript apply() method - complete guide with examples
Related JavaScript Master Course Topics