Calling JavaScript Functions: Methods, this, Constructors, Recursion and the Call Stack
The five ways a JavaScript function gets called, and how each one decides the value of this: plain calls, method calls, constructors with new, call/apply/bind, and implicit calls. Losing this in callbacks and its fixes, method chaining, recursion, the call stack and stack overflow.
kvi5hnuCode Sprout team member8 min readOn this page
Defining a function doesn't run it; calling (invoking) it does. JavaScript has several ways to call a function, and they differ in one crucial respect: the value of this inside it. Misunderstanding this causes some of the most common JavaScript bugs, so this article goes through every case.
The five kinds of call
- As a function:
formatPrice(9.5) - As a method:
cart.addItem(book) - As a constructor:
new Date(2024, 0, 1) - Indirectly:
greet.call(user, "hi"),greet.apply(user, ["hi"]) - Implicitly, by language features that don't look like calls: getters and setters,
toString/valueOfconversions, iteration, tagged templates, proxies.
In every case, the argument expressions are evaluated first (left to right) and their values passed to the parameters. What differs is this and, for constructors, the return value.

Function invocation
A plain call like fn() is a function invocation. The result of the call expression is the function's return value, or undefined if it doesn't return one.
The optional-call operator ?.() (article 30) calls a function only if it isn't null or undefined: onDone?.(result) is a common way to call an optional callback.
In a plain call, this is undefined in strict code (modules, classes, "use strict"), and the global object in sloppy-mode scripts:
function strictThis() {
"use strict";
return this;
}
// new Function always creates sloppy-mode code, even inside a module
const sloppyThis = new Function("return this === globalThis");
console.log(strictThis(), sloppyThis());
undefined true
Strict mode's undefined is much safer: code that wrongly uses this fails immediately instead of quietly reading and writing global variables. Functions meant to be called as plain functions usually don't use this at all.
Method invocation
A method is a function stored in an object property. Calling it through the object (obj.method() or obj["method"]()) makes that object the invocation context: this inside the method refers to it.
const wallet = {
owner: "Ana",
balance: 20,
spend(amount) {
this.balance -= amount;
return `${this.owner} has ${this.balance} left`;
},
};
console.log(wallet.spend(5));
console.log(wallet["spend"](3));
Ana has 15 left
Ana has 12 left
The key insight: this is decided at call time by how the function is called, not by where it was defined. The same function behaves differently when called through different objects:
function introduce() {
return `I am ${this.name}`;
}
const robot = { name: "R2", introduce };
const person = { name: "Ana", introduce };
console.log(robot.introduce(), person.introduce());
I am R2 I am Ana
Method chaining
When a method has nothing more useful to return, returning this lets callers chain calls on the same object:
const query = {
parts: [],
select(fields) { this.parts.push(`SELECT ${fields}`); return this; },
from(table) { this.parts.push(`FROM ${table}`); return this; },
where(cond) { this.parts.push(`WHERE ${cond}`); return this; },
build() { return this.parts.join(" "); },
};
console.log(query.select("name").from("users").where("age > 18").build());
SELECT name FROM users WHERE age > 18
jQuery, query builders, test assertions (expect(x).to.be.a("string")) and many other libraries use this style. Array methods and promises chain too, but differently: they return new objects rather than this.
Losing this
Because this depends on the call, taking a method out of its object and calling it as a plain function loses this:
"use strict";
const counter = {
count: 0,
increment() {
this.count++;
},
};
const detached = counter.increment;
try {
detached(); // plain call: this is undefined
} catch (err) {
console.log(err.name);
}
TypeError
This happens whenever you pass a method as a callback: setTimeout(counter.increment, 100), button.addEventListener("click", counter.increment), promise.then(service.handle). The receiving code calls it as a plain function, so this is undefined (or, in DOM event handlers, the element).
Nested functions don't inherit this
The same trap appears inside methods. A regular function defined inside a method gets its own this, decided by how it is called:
"use strict";
const team = {
name: "Red",
members: ["Ana", "Bo"],
labelsBroken() {
return this.members.map(function (m) {
return `${m} (${this?.name})`; // this is undefined here
});
},
labels() {
return this.members.map((m) => `${m} (${this.name})`); // arrow: the method's this
},
};
console.log(team.labelsBroken());
console.log(team.labels());
[ 'Ana (undefined)', 'Bo (undefined)' ]
[ 'Ana (Red)', 'Bo (Red)' ]
The fixes
- Arrow functions (the modern default): an arrow doesn't have its own
this; it uses thethisof the code around it, fixed when the arrow is created. Perfect for callbacks inside methods. bind:counter.increment.bind(counter)returns a new function whosethisis permanentlycounter(article 68).- A wrapper arrow at the call site:
setTimeout(() => counter.increment(), 100)calls it as a method again. const self = this: the pre-2015 idiom, still seen in older code; the nested function usesselfinstead ofthis.- Class fields with arrows:
handleClick = () => {...}inside a class gives each instance a function bound to it (part 9), common in React class components.
"use strict";
const counter = {
count: 0,
increment() {
this.count++;
},
};
const bound = counter.increment.bind(counter);
bound();
const run = (fn) => fn(); // stands in for setTimeout, an event listener...
run(bound);
run(() => counter.increment());
console.log(counter.count);
3
The flip side: don't use arrow functions as methods in object literals. An arrow method's this is the this of the code where the object literal appears (usually undefined in a module), not the object.
Constructor invocation
Calling a function with new makes it a constructor call (articles 46 and part 9). new does four things:
- creates a new empty object;
- sets its prototype to the function's
prototypeproperty; - calls the function with
thisset to the new object; - returns the new object, unless the function explicitly returns another object.
function Point(x, y) {
this.x = x;
this.y = y;
}
Point.prototype.length = function () {
return Math.hypot(this.x, this.y);
};
const p = new Point(3, 4);
console.log(p, p.length(), p instanceof Point);
Point { x: 3, y: 4 } 5 true
If the constructor returns an object, that object replaces the new one; returning a primitive is ignored:
function ReturnsObject() {
this.a = 1;
return { replaced: true };
}
function ReturnsPrimitive() {
this.a = 1;
return 42;
}
console.log(new ReturnsObject(), new ReturnsPrimitive());
{ replaced: true } ReturnsPrimitive { a: 1 }
Forgetting new with an old-style constructor function is a classic bug: Point(1, 2) runs as a plain call, so in strict mode it throws (this is undefined), and in sloppy mode it creates global variables x and y. Classes (part 9) solve this: calling a class without new always throws a TypeError. Inside a function, new.target tells you whether it was called with new.
Empty parentheses are optional with new (new Date works), but omitting them hurts readability.
Indirect invocation: call and apply
Every function has call and apply methods, which call it with an explicit this. call takes the arguments one by one, apply as an array:
function describe(greeting, punctuation) {
return `${greeting}, ${this.name}${punctuation}`;
}
const user = { name: "Bo" };
console.log(describe.call(user, "Hello", "!"));
console.log(describe.apply(user, ["Hi", "?"]));
Hello, Bo!
Hi, Bo?
They let you use a method on an object that doesn't have it, as with borrowing array methods (article 62). Since spread arrived, fn.apply(null, args) is usually written fn(...args). Article 68 covers call, apply and bind in depth.
Implicit invocation
Some functions run without any visible call:
- Getters and setters run on property reads and writes (article 53).
toString,valueOfandSymbol.toPrimitiverun when objects are converted (articles 31 and 51).- Iterator methods run during
for...of, spread and destructuring (part 12). - Tagged templates call their tag function:
tag`text ${value}`(part 14). - Proxy traps run on almost any operation on a proxy (part 14).
- Callbacks passed to built-ins: array methods,
sortcomparators,JSON.parserevivers, event listeners.
Bugs in implicitly called code are harder to find because nothing at the call site shows that a function runs. Keep such functions simple and free of surprising side effects.
Recursion and the call stack
A recursive function calls itself. Each call solves a smaller version of the problem until it reaches a base case that's answered directly:
function totalSize(folder) {
let size = folder.files ?? 0; // base case: no subfolders
for (const sub of folder.subfolders ?? []) {
size += totalSize(sub); // recursive case
}
return size;
}
const projectFolder = {
files: 3,
subfolders: [{ files: 5 }, { files: 1, subfolders: [{ files: 2 }] }],
};
console.log(totalSize(projectFolder));
11
Recursion is natural for tree-shaped data: folders, the DOM, JSON, menus, comment threads, and algorithms like quicksort and depth-first search.
The call stack
The engine keeps track of active calls on the call stack. When a function is called, a frame (its arguments, local variables and where to return to) is pushed onto the stack; when it returns, the frame is popped. Recursion pushes one frame per level, and the stack has a limited size. Exceed it, and you get a RangeError, the famous "Maximum call stack size exceeded":
function forever(n) {
return forever(n + 1); // no base case
}
try {
forever(0);
} catch (err) {
console.log(err.name, err instanceof RangeError);
}
RangeError true
The limit depends on the engine and the size of each frame, typically around ten thousand calls. For data that might be very deep (a long linked list, a huge nested structure), use a loop with an explicit stack array instead. The specification includes proper tail calls, which would allow unlimited recursion in some cases, but only Safari implements them, so you can't rely on them.
Stack traces in error messages (err.stack) are a printout of the call stack at the moment the error was created: reading them from top to bottom shows which function called which.
Common questions
What's the difference between a function and a method?
Only how it's called. A method is a function stored in an object property and called through that object, which sets this. The same function can be called both ways.
Why is this undefined in my callback?
The callback was called as a plain function, so it didn't get your object as this. Use an arrow function for the callback, or pass a bound function (this.handle.bind(this)).
Can I assign to this?
No. this is a keyword, not a variable; this = x is a SyntaxError. You choose this by how you call the function, or with call, apply and bind.
Should I use recursion or loops?
Use recursion when the data or problem is naturally recursive (trees, nested structures) and depth is bounded. Use loops for simple repetition and for potentially very deep data, to avoid stack overflows.
Summary
- Functions are called as plain functions, methods, constructors (
new), indirectly (call,apply) or implicitly. thisis decided by how a function is called: the object before the dot for methods, the new object fornew, the given object forcall/apply/bind,undefined(strict) or the global object (sloppy) for plain calls.- Arrow functions don't have their own
this; they use the surrounding one. Use them for callbacks, not for object methods. - Passing a method as a callback loses
this; fix it with an arrow wrapper orbind. newcreates an object linked to the constructor'sprototypeand returns it, unless the constructor returns another object.- Recursion needs a base case; each call uses a stack frame, and too many cause a
RangeError.
Practice Questions
In strict mode, what does this print?
const o = { n: 1, get() { return this?.n; } };
const g = o.get;
console.log(o.get(), g());
Answer
1 undefined. o.get() is a method call, so this is o. g() is a plain call, so this is undefined, and ?. avoids the TypeError.
Why doesn't this work, and how do you fix it?
const timer = { secs: 0, start() { setInterval(function () {
this.secs++;
}, 1000); } };
Answer
The callback is a regular function called by the timer as a plain function, so this isn't timer. Use an arrow function: setInterval(() => { this.secs++; }, 1000).
What does new F() return for this constructor?
function F() {
this.x = 1;
return [2];
}
Answer
[ 2 ]. An array is an object, so it replaces the newly created object.
Write a recursive depth(obj) that returns the maximum nesting depth of arrays, where depth(5) is 0 and depth([1, [2, [3]]]) is 3.
Answer
const depth = (v) => (Array.isArray(v) ? 1 + Math.max(0, ...v.map(depth)) : 0);
The 0 inside Math.max handles empty arrays, so depth([]) is 1.
Previous: JavaScript Functions: Declarations, Expressions and Arrow Functions
Next: JavaScript Function Parameters: Defaults, Rest Parameters, arguments, Spread and Destructuring

More in JavaScript Course
Quiz: Modern JavaScript, ES2022 to ES2027 Features
Twenty-four questions on what's new in JavaScript: change-array-by-copy methods, groupBy, Set methods, iterator helpers, Promise.withResolvers and Promise.try, RegExp.escape and the v flag, using declarations, Error.isError, Base64 typed arrays, Temporal, getOrInsert and Iterator.zip.
Quiz: JavaScript's Delicate Details (Spec-Level Edge Cases)
Twenty-eight questions on the fine print of JavaScript, drawn from the ECMAScript specification and MDN: sparse arrays, -0, number limits, JSON edge cases, Date overflow, UTF-16, property attributes, inherited accessors, comparison quirks, labels, regex state and Symbol.toPrimitive.
Quiz: JavaScript Interview Questions (Output Prediction and Core Concepts)
Thirty classic JavaScript interview questions: closures in loops, hoisting and the TDZ, this, the event loop and microtasks, async/await, coercion, sorting and parseInt traps, prototypes, copying, finally, generators and bind. Every answer was verified by running it.
Quiz: JavaScript Course Final Exam (All 17 Parts)
The final exam for the JavaScript course: thirty questions spanning all seventeen parts, from syntax, types and operators through objects, arrays, functions, classes, modules, the standard library, iterators, async code, metaprogramming, browsers, Node.js and tooling.
Discussion
Sign in to ask a question or share what you learned.