Interview Q&A / Object-Oriented Programming

BeginnerQuick answer1 min readUpdated 3 Oct 2026

How do you do dependency injection in JavaScript without any framework?

SHORT ANSWER

Pass the dependency as an argument, either to a factory function or a class constructor. A function that receives what it needs is already using dependency injection.

Explain it simply

A framework is not required for DI. If a cook is given the stove to use, rather than building one, that is DI. In JavaScript, a plain function that takes the clock, the logger or the database as parameters does the job.

Example

js
function createGreeter(clock) {
  return function greet(name) {
    const hour = clock.hour();
    return (hour < 12 ? "Good morning" : "Good evening") + ", " + name;
  };
}

const realClock = { hour: () => new Date().getHours() };
const morningClock = { hour: () => 9 };
const eveningClock = { hour: () => 19 };

const testGreeter = createGreeter(morningClock);
console.log(testGreeter("Neha"));                       // Output: Good morning, Neha
console.log(createGreeter(eveningClock)("Neha"));       // Output: Good evening, Neha

const liveGreeter = createGreeter(realClock);           // production wiring

The same trick works with classes: new Greeter(clock). Tests pass fixed clocks, so results do not depend on the time of day they run.

What to say in the interview

"Dependencies can simply be parameters, either of a function, a factory or a class constructor. I wire real implementations at the application entry point and pass fakes in tests. A container is a convenience, not a requirement."

Common mistakes

  • Importing a module-level singleton inside the function. That is hidden coupling that tests cannot replace easily.

#dependency-injection#javascript#functions

Related questions

Practise more Object-Oriented Programming questions

Test your recall with short answers, then return to the detailed explanations when you need context.

Open Object-Oriented Programming quick answers →

Get new questions like this by email

One short email when something new and useful lands. No spam, unsubscribe in one tap.

By subscribing you agree to the Privacy Policy.