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.

First-Class Functions, Callbacks & Closures

JavaScript treats functions as first-class citizens, meaning they behave like normal values:

  • Stored in variables
  • Passed into other functions as arguments
  • Returned from functions
  • Assigned as object properties

This capability enables three foundational pillars of modern JavaScript:

  1. First-Class Functions
  2. Callbacks
  3. Closures

Together, these form the backbone of asynchronous programming, event handling, functional programming, React hooks, and Node.js architecture.

1. First-Class Functions

A language has first-class functions when functions behave like normal values (numbers, strings, objects).

Functions Stored in Variables

You can store a function in a variable just like any standard value:

variable-function.js
const greet = function () {
  console.log("Hello!");
};

greet(); // Output: Hello!

Functions Passed as Arguments

You can send a function as a parameter into another function, and that receiving function can execute it.

🧠 Think of it like giving a tool to a machine:

  • You provide run() with a tool (a function).
  • Inside run(), it uses that tool: tool().
  • In memory, the parameter fn points directly to the function you passed in.
passing-functions.js
function run(fn) {
  fn(); // <-- Executes the function received
}

run(() => console.log("Running..."));
// Output: Running...
fn is not a number or a string—it is a function parameter that run() invokes.

Functions Returned from Other Functions

Functions can generate and return new functions, enabling factory functions and function generators:

multiplier-factory.js
function makeMultiplier(x) {
  return function (y) {
    return x * y;
  };
}

const double = makeMultiplier(2);
console.log(double(5)); // Output: 10

2. Callbacks

A callback is a function passed into another function to run later.

Callbacks appear everywhere in JavaScript:

  • Timers (setTimeout, setInterval)
  • Event listeners (element.addEventListener)
  • Array methods (map, filter, reduce)

Callbacks allow asynchronous, non-blocking execution—JavaScript continues running other code while waiting for events or timers.

callback-patterns.js
// 1. Simple Custom Callback
function greet(name, callback) {
  console.log("Hello " + name);
  callback();
}

greet("Mohammed", () => console.log("Welcome!"));
// Output:
// Hello Mohammed
// Welcome!

// 2. Array Callback Example
const nums = [1, 2, 3];
const doubled = nums.map(n => n * 2);
console.log(doubled); // Output: [2, 4, 6]

// 3. Asynchronous Callback Example
setTimeout(() => {
  console.log("This runs later");
}, 2000);
// Output after 2 seconds: This runs later
Callbacks allow JavaScript to handle events and async operations without freezing execution.

3. Closures (The Heart of JavaScript)

A closure happens when an inner function "remembers" and retains access to variables from its outer lexical scope—even after the outer function has finished executing.

Closures allow:

  • Private variables (Encapsulation)
  • Factory functions
  • Function generators
  • Event handler logic & stateful callbacks
  • Module patterns
Diagram showing returned function maintaining reference to outer lexical environment.
The returned function retains a live reference to its outer environment even after the factory call finishes.
closure-examples.js
// 1. Basic Closure
function outer() {
  let count = 0;
  return function inner() {
    count++;
    console.log(count);
  };
}

const counter = outer();
counter(); // 1
counter(); // 2
counter(); // 3

// 2. Encapsulation & Private Data
function createUser(name) {
  let score = 0;
  return {
    getName: () => name,
    addPoint: () => score++,
    getScore: () => score
  };
}

const user = createUser("Sara");
user.addPoint();
user.addPoint();

console.log(user.getName());  // Output: Sara
console.log(user.getScore()); // Output: 2
console.log(user.score);      // Output: undefined (score is truly private!)
Even though outer() and createUser() finished, the inner functions preserve access to count and score.

Closures + Callbacks Working Together

When you pass a callback or create an event listener, closures allow that callback to carry its surrounding state with it:

closure-callback.js
function setupButton(text) {
  return function handleClick() {
    console.log("Clicked: " + text);
  };
}

const clickFn = setupButton("Save");
clickFn(); // Output: Clicked: Save
handleClick carries the text variable from setupButton even when invoked elsewhere.
Characteristics Summary: The Three Pillars at a Glance

Pillar

Definition

Key Powers

Common Use Cases

First-Class Functions

Functions behave like standard values

Can be stored in variables, passed as args, and returned

Higher-order functions, functional programming, React components

Callbacks

A function passed to another function to run later

Enables non-blocking asynchronous & event-driven execution

setTimeout, DOM events, array methods (map, filter, reduce)

Closures

Inner function captures outer lexical scope variables

Encapsulates private data and preserves state across function calls

Factory functions, private state, React useState, memoization

Think it throughQuick Interview Check: How do First-Class Functions, Callbacks, and Closures work together in array methods?

Consider nums.map(n => n * multiplier):

  1. First-class functions allow passing n => n * multiplier as an argument.
  2. That passed function is a callback that .map() invokes on each array element.
  3. It forms a closure over multiplier from the surrounding scope, reading its value on every iteration.