0

So, I created an http server in node to which I passed a callback that increments a global variable 'reqCounter', but I don't understand how it is incrementing it, how does createServer have access to 'reqCounter' isn't it defined somewhere else?

let reqCounter = 0;

const server = http.createServer((req, res) => {
    res.end('Server has been accessed');
    reqCounter++;
    console.log('Incoming request' + ` ${reqCounter}`);
});

Isn't the context that createServer is defined in different from where reqCounter is defined?

Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
FNER
  • 29
  • 5
  • The variable and the function are both inside whatever context they're in. What you're saying would be true if the variable were defined in some other block context. – isherwood Sep 27 '21 at 20:05
  • it wouldn't have worked if 'a' wasn't a callback and we just incremented counter inside incrementCounter, how is it different for callbacks? – FNER Sep 27 '21 at 20:48
  • Sorry, but you can’t just edit the question into a _completely different_ one. Ask a new question instead. CC @bereal – Sebastian Simon Sep 27 '21 at 21:18

0 Answers0