0

I'm coming from a Java background and I a way to make use of incoming data to a node.js server:

request.addListener("data", function(postDataChunk) {
  postData += postDataChunk;
  console.log("Received POST data chunk '"+
  postDataChunk + "'.");
});

as I have seen the postData variable is allways receiving new data and adds it to the existing. My question is: every time the data event is occuring the callback function is executed, but in the way I see it, every new time the function is being called we are actually getting a new variable "postData". So I do not understand how exactlly the postData variable is actually being updated every time and not being created as a new variable as it would have been in regular Java.

Thanks.

paary
  • 421
  • 6
  • 16
lobengula3rd
  • 1,821
  • 4
  • 26
  • 39

1 Answers1

2

If you use var postData, it would do the same as it would in JAVA but here postData is a global variable that gets incremented. In JavaScript, if you don't explicitly write the keyword var, the variable is automatically instantiated on first call and then used as if it was a global variable.

Hopefully, the answer to this question would make things clear.

EXAMPLE
What you wrote is essentially;

request.addListener("data", function(postDataChunk) {
  /*"var" omitted in function!
   *creates variable "window['postData']"
   *unless already created*/
  postData += postDataChunk;
  console.log("Received POST data chunk '"+
  postDataChunk + "'.");
});

Scoping to the function using var

request.addListener("data", function(postDataChunk) {
  //"var" keyword used! variable created in this scope!
  var postData += postDataChunk;
  console.log("Received POST data chunk '"+
  postDataChunk + "'.");
});
Community
  • 1
  • 1
U.P
  • 7,357
  • 7
  • 39
  • 61