JavaScript Closures and Shared State in Node.js

This looks obvious… until it isn’t 👀 Most Node.js devs answer this too fast. No frameworks. No libraries. Just JavaScript fundamentals. Question 👇 function createCounter() { let count = 0; return { inc() { count++; }, get() { return count; } }; } const counter1 = createCounter(); const counter2 = createCounter(); counter1.inc(); counter1.inc(); counter2.inc(); console.log(counter1.get(), counter2.get()); ❓ What will be printed? A. 2 1 B. 3 3 C. 1 1 D. 2 2 👇 Drop ONE option only in the comments Why this matters Many developers know closures… but still get confused about: shared vs isolated state how function scope actually works why two “similar” objects behave differently When fundamentals aren’t clear: bugs feel random state becomes unpredictable debugging turns into guesswork Good engineers don’t just write code. They understand why it behaves this way. Did this one make you pause? 👀 #NodeJS #JavaScript #WebDevelopment #fullstackDeveloper #CodingChallenge #reactDeveloper 😊 #ProgrammingFundamentals #Closures #StateManagement #SoftwareEngineering #Debugging #DeveloperCommunity

  • text

2,1 Each function creates their own context hence closures formed will be independent.

2,1 because both counter1 and counter2 have independent count

A: 2 1. We have two separate closures with their own private counts!!

A. 2, 1. There are two functions with two separate closures, each having its respective counter variable being incremented.

Like
Reply

Answer A, 2.1, if we pretend that the returned object isn't missing a comma😄

Like
Reply
See more comments

To view or add a comment, sign in

Explore content categories