Find a subject or note

13 results found

JavaScriptArray Methods, Loop Mechanics & The Async Trap

Mastering slice vs splice, search & reduce patterns, loop intent (for...in vs for...of vs map), and the async forEach trap.

JavaScriptasync / await & Modern Asynchronous Flow

Mastering async functions, the non-blocking await keyword, error handling with try/catch, and avoiding performance waterfalls.

JavaScriptcall(), apply(), bind() (Controlling this)

How to explicitly control function execution context in JavaScript using call, apply, and bind.

JavaScriptErrors, try/catch & Defensive Design

Understanding built-in error types, the Error object, custom error classes, async handling, and defensive validation patterns.

JavaScriptThe Event Loop

How JavaScript coordinates synchronous code, the Call Stack, Microtask Queue, and Macrotask Queue.

JavaScriptFetch API, HTTP & Web APIs

HTTP fundamentals, URLSearchParams, response handling, CORS, AbortController, and production service layers.

JavaScriptFirst-Class Functions, Callbacks & Closures

How first-class functions, callbacks, and closures connect to form the foundation of modern JavaScript.

JavaScriptObject Utilities (keys, values, entries, fromEntries)

How Object.keys, Object.values, Object.entries, and Object.fromEntries bridge objects and arrays in JavaScript.

JavaScriptPromises & Promise Combinators

Understanding asynchronous execution, Promise lifecycles, error propagation, and Promise combinators (all, allSettled, race, any).

JavaScriptReturn, Scope & Hoisting in Functions

How return statements, lexical scope, and hoisting determine how functions execute in JavaScript.

JavaScriptSecurity Basics: XSS & Safe DOM Rendering

Cross-Site Scripting (XSS) mechanics, safe DOM manipulation, innerHTML vs textContent, and the validation vs sanitization pipeline.

JavaScriptShallow vs. Deep Copy (Spread Pitfalls & JSON Limits)

Understanding object references, shallow copy pitfalls with spread, JSON limitations, and structuredClone.

JavaScriptWeb Storage: localStorage, sessionStorage & Cookies

Client-side storage mechanisms in JavaScript: comparing localStorage, sessionStorage, and Cookies for interview prep.

call(), apply(), bind() (Controlling this)

In JavaScript, the this keyword is not determined by where a function is written—it is determined by how the function is called at runtime. When methods are extracted or passed into callbacks, their execution context is often detached and lost.

To command this explicitly, JavaScript provides three built-in Function.prototype methods:

  • 🔹 call()
  • 🔹 apply()
  • 🔹 bind()
Diagram comparing call, apply, and bind in JavaScript
call and apply execute immediately with explicit context; bind returns a new permanently bound function.

Why Controlling this Matters

When you assign an object method to a variable or pass it as a callback, this loses its binding to the original object:

lost-context.js
const user = {
  name: "Ali",
  greet() {
    console.log(this.name);
  }
};

const sayHello = user.greet;
sayHello(); // ❌ Output: undefined (this is lost!)
Because sayHello() was invoked as a plain standalone function, this defaulted to the global object or undefined in strict mode.

1. call() – Invoke Immediately with this

call() invokes the function immediately and explicitly sets this to the provided object. Additional arguments are passed individually as a comma-separated list.

Syntax

fn.call(thisValue, arg1, arg2, ...);

2. apply() – Arguments as an Array

apply() is identical to call(), except that arguments are packed inside an array.

Syntax

fn.apply(thisValue, [arg1, arg2, ...]);
call-vs-apply.js
function greet(greeting, punctuation) {
  console.log(`${greeting}, ${this.name}${punctuation}`);
}

const user = { name: "Sara" };

// 1. call() - Arguments listed individually
greet.call(user, "Hello", "!"); // Output: "Hello, Sara!"

// 2. apply() - Arguments packed in an array
greet.apply(user, ["Hi", "..."]); // Output: "Hi, Sara..."
Both execute immediately; the only difference is comma-separated vs array arguments.

3. bind() – Lock this for Later

Unlike call() and apply(), bind() does NOT execute the function immediately. Instead, it returns a brand-new copy of the function with this permanently locked to the provided context.

Syntax

const boundFn = fn.bind(thisValue, arg1, arg2, ...);
bind-examples.js
function greet(greeting) {
  console.log(`${greeting}, ${this.name}`);
}

const user = { name: "Sara" };

// bind() returns a new function with 'this' permanently locked
const boundGreet = greet.bind(user, "Hello");
boundGreet(); // Output: "Hello, Sara"

// Real-World Pattern: Preserving 'this' in Class Event Handlers
class Counter {
  constructor() {
    this.count = 0;
    // Lock 'this' to the instance so callbacks don't break
    this.inc = this.inc.bind(this);
  }

  inc() {
    this.count++;
    console.log(this.count);
  }
}
Without bind(this), passing this.inc into addEventListener or setTimeout causes this to be lost.
call() vs. apply() vs. bind() Comparison

Method

Execution Timing

Arguments Format

Return Value

Primary Use Case

call()

Executes immediately

Comma-separated list (arg1, arg2)

Result of function call

One-time immediate call with custom context

apply()

Executes immediately

Single array of args ([arg1, arg2])

Result of function call

Invoking functions with pre-existing argument arrays

bind()

Does NOT execute now

Comma-separated list (arg1, arg2)

New bound function copy

Event handlers, callbacks, and partial function application

Think it throughInterview Question: What does this print, and why?
const person = {
  name: "Alex",
  greet: () => {
    console.log(this.name);
  }
};
person.greet.call({ name: "Jordan" });

Output: undefined (or global name in browsers)

Why? greet is an arrow function. Arrow functions have no execution-context this of their own—they capture this lexically from their parent scope (here, the outer/global scope). Calling .call(), .apply(), or .bind() on an arrow function is silently ignored and will not alter its context.