1

I feel like this is a pretty stupid question, but I'm having trouble understanding why I'm seeing strange behavior in a callback function. I defined an array called clientList which I export and use in other files. This code here is run when a client connects to my server.

When I say clientList.splice or clientList.push, everything works as expected, and the clinetList array reflects my change in other files which require() it in. However, if I say assign ClientList directly (e.g. clientList = []) then that change is not reflected in other files. If I print the contents of ClientList inside the callback, the change is reflected either way.

var clientList = [];

module.exports.socketHandler = (socket) => {
var client = new Client(socket);
clientList.push(client);

socket.on('end',function(){
    clientList = [] //This does not change the exported array
    clientList.splice(0,1); //This does change the exported array
    console.log("Client connection ended: "+clientList.length); //This always changes
});

}

module.exports.clientList = clientList;


//IN A DIFFERENT FILE
//This code is run every few seconds on a loop
var example = require('./sockets.js');
console.log("Array Size: "+example.clientList.length);

My question is why there is a difference here. I have a good understanding of javascript scope and asynchronous operations, but I'm having a hard time figuring out what's causing this behavior. Is this related to how the node module loader works? Or am I just missing something obvious? Any help would be appreciated.

Pancake
  • 143
  • 5
  • 12
  • 2
    [Is JavaScript a pass-by-reference or pass-by-value language?](https://stackoverflow.com/questions/518000/is-javascript-a-pass-by-reference-or-pass-by-value-language) – Andreas Dec 21 '16 at 08:45
  • That's interesting. I know that javascript passes values in this way, but since I didn't explicitly pass any arguments it didn't occur to me. So even if you just reference a variable in the parent scope, the same rules apply? – Pancake Dec 21 '16 at 08:50
  • 1
    When you have got refrences to an array you should'nt empty it like that. use other methods like `clientList.lenght=0`. See: [how-do-i-empty-an-array-in-javascript](http://stackoverflow.com/a/1232046/5048383) – dNitro Dec 21 '16 at 08:55

1 Answers1

1

The problem is exactly in this line:

clientList = [] //This does not change the exported array

Doing this you are not emptying the array, but assigning a new one in that variable. But you already exported the old one, so that's because it's not being reflected in the other files.

Someone already put in the comments how to empty an array, in your case I would use method 2 or 3 (2 is the most common one I'd say).

Community
  • 1
  • 1
Antonio Val
  • 3,200
  • 1
  • 14
  • 27