DEV Community

Karen Molina
Karen Molina

Posted on Edited on

Frontend interview prep: functions and closures in JavaScript

Updated in 2026. I wrote the first version of this post in 2021 while preparing for interviews. I've rewritten it with clearer explanations, a fixed closure example (the original one had a bug!) and model answers.

If there's one JavaScript topic that appears in almost every frontend interview, it's closures. And you can't really understand closures without understanding functions first. So let's start there.

Functions are values

A function is a reusable block of code that performs a task. In JavaScript, functions are also first-class objects: you can store them in variables, pass them as arguments, return them from other functions and even add properties to them.

That single idea is what makes callbacks, event handlers, React components and closures possible.

Anatomy of a JavaScript function

There are several ways to create a function, and the differences matter in interviews.

Function declaration

The classic form: the function keyword, a name, parameters and a body.

function sum(a, b) {
  return a + b;
}

sum(2, 4); // 6
Enter fullscreen mode Exit fullscreen mode

Function declarations are fully hoisted, so you can call them before the line where they're written.

Function expression

A function created as part of an expression, usually assigned to a variable.

const sum = function (a, b) {
  return a + b;
};

sum(2, 4); // 6
Enter fullscreen mode Exit fullscreen mode

It looks almost the same, but there's a key difference: only the variable is hoisted, not the function. Calling it before that line fails.

greet();      // works: declaration
sayBye();     // ReferenceError (const) or TypeError (var)

function greet() { console.log("hi"); }
const sayBye = function () { console.log("bye"); };
Enter fullscreen mode Exit fullscreen mode

Arrow functions

Introduced in ES6 (2015). Shorter syntax, and if the body is a single expression, it's returned automatically.

const sum = (a, b) => a + b;

sum(2, 4); // 6

// To return an object literal, wrap it in parentheses
const makeUser = (name) => ({ name });
Enter fullscreen mode Exit fullscreen mode

But arrow functions aren't just shorter syntax. They behave differently:

  • No own this. They use the this of the surrounding code. Great for callbacks, bad for object methods.
  • No arguments object. Use rest parameters (...args) instead.
  • Can't be used with new. new (() => {}) throws TypeError: ... is not a constructor.
const timer = {
  seconds: 0,
  start() {
    setInterval(() => {
      this.seconds++; // `this` is still `timer`, thanks to the arrow function
    }, 1000);
  },
};
Enter fullscreen mode Exit fullscreen mode

With a regular function inside setInterval, this would no longer point to timer. That's a very common interview follow-up.

IIFE (Immediately Invoked Function Expression)

A function that runs as soon as it's defined.

(function () {
  const secret = "only visible in here";
  console.log("Hello world");
})();
Enter fullscreen mode Exit fullscreen mode

Before ES modules and let/const, IIFEs were the main way to create a private scope and avoid polluting the global one. You'll still see them in older code and in interview questions.

Constructor functions and classes

A constructor function creates objects when called with new.

function User(first, last) {
  this.firstName = first;
  this.lastName = last;
}

const user = new User("Jon", "Snow");
// { firstName: "Jon", lastName: "Snow" }
Enter fullscreen mode Exit fullscreen mode

When you use new, JavaScript:

  1. creates a new empty object,
  2. links it to the constructor's prototype,
  3. runs the function with this pointing to that object,
  4. returns the object (unless the function explicitly returns another object).

Today you'll usually write the same thing with class, which is mostly syntax on top of the same mechanism:

class User {
  constructor(first, last) {
    this.firstName = first;
    this.lastName = last;
  }
}
Enter fullscreen mode Exit fullscreen mode

Interview answer: "Functions in JavaScript are first-class objects. Function declarations are fully hoisted; function expressions aren't. Arrow functions are shorter and don't have their own this or arguments, and they can't be used as constructors. Constructor functions and classes create objects with new, which sets this to a new object linked to the prototype."

Closures

The definition

A closure is a function that remembers the variables from the scope where it was created, even after that outer scope has finished running.

Every function in JavaScript forms a closure. It's not a special syntax; it's a consequence of functions being values and of the scope chain.

The example

In the first version of this post, my example had a bug: I called the outer function and expected it to print. Here's the corrected version:

function sayHi() {
  const greeting = "Hola";

  function inner() {
    console.log(greeting);
  }

  return inner;
}

const hi = sayHi(); // sayHi has finished running...
hi();               // ...but inner still remembers `greeting`: "Hola"
Enter fullscreen mode Exit fullscreen mode

sayHi has already returned, so in theory greeting should be gone. But inner keeps a reference to the scope where it was created, so greeting stays alive as long as inner exists.

Why it's useful: private state

Closures let you create data that can't be accessed from the outside.

function createCounter() {
  let count = 0;

  return {
    increment() {
      count++;
      return count;
    },
    get() {
      return count;
    },
  };
}

const counter = createCounter();
counter.increment();
counter.increment();

counter.get();  // 2
counter.count;  // undefined: there's no way to touch `count` directly
Enter fullscreen mode Exit fullscreen mode

The classic interview question

You'll probably see this one:

for (var i = 0; i < 3; i++) {
  setTimeout(() => console.log(i));
}
// 3, 3, 3
Enter fullscreen mode Exit fullscreen mode

Why 3, 3, 3 and not 0, 1, 2? Because var is function-scoped, there's only one i. All three callbacks close over the same variable, and by the time they run, the loop has finished and i is 3.

The fix is let, which creates a new binding for each iteration:

for (let i = 0; i < 3; i++) {
  setTimeout(() => console.log(i));
}
// 0, 1, 2
Enter fullscreen mode Exit fullscreen mode

Closures in real life: React

If you use React, you're using closures every day. Every render creates new functions that close over that render's props and state. That's the root of the famous "stale closure" bug:

function Counter() {
  const [count, setCount] = useState(0);

  useEffect(() => {
    const id = setInterval(() => {
      setCount(count + 1); // always sees the `count` from the first render
    }, 1000);
    return () => clearInterval(id);
  }, []);

  return <p>{count}</p>; // gets stuck at 1
}
Enter fullscreen mode Exit fullscreen mode

The interval callback closed over count = 0 and never sees updates. The fix is the functional update, which doesn't depend on the closed-over value:

setCount((c) => c + 1);
Enter fullscreen mode Exit fullscreen mode

Mentioning this in an interview shows you understand closures beyond the textbook definition.

Interview answer: "A closure is a function that keeps access to the variables of the scope where it was created, even after that scope has finished. It's used for private state, factories, callbacks and memoization. A classic example is the var loop with setTimeout printing the same value three times, which let fixes because it creates a new binding per iteration. In React, stale closures in effects are a common bug caused by the same mechanism."

Quick checklist

  • [ ] Can you explain why functions are "first-class objects"?
  • [ ] Do you know which function forms are hoisted and which aren't?
  • [ ] Can you name three differences between arrow functions and regular functions?
  • [ ] Can you explain what new does, step by step?
  • [ ] Can you define a closure in one sentence and give an example?
  • [ ] Can you explain the var + setTimeout loop output?

Previous in the series: variables, data types, scope and hoisting.
Next: asynchronous JavaScript: callbacks, promises and async/await.

What was your "aha" moment with closures? Tell me in the comments 👇

Top comments (1)

Collapse
 
rameshkmunjal profile image
RAMESH KUMAR MUNJAL •

Good article. Concisely discussed all types of functions at one place.