How do you do dependency injection in JavaScript without any framework?
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
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 wiringThe 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.