Eunice Chia Eunice Chia - 1 year ago 88
Node.js Question

Closure confusion, share global variable between function

var data = null;

socket.on('screen1', function (data) {

data = data;
console.log(data) // has something

console.log(data) //null
socket.emit('screen2', data);


For some reason I can't put click event into socket.on because it's listening to the server. But I want its callback which is the
.I tried to do data = data and expect my click callback is able to get the data but it's still null.

Answer Source

Your local variable takes precedence over the global variable:

socket.on('screen1', function (data) { // <-- local variable "data"
    data = data;  // <-- both these "data" are the same variable!!

To access the global variable "data" rename the local variable to something else:

socket.on('screen1', function (d) {
    // Here I have no idea what your intention is. If I am
    // confused consider how the compiler is supposed to read
    // your mind.

    // You either wanted to do:
    d = data;

    // or data = d;

    // I cannot guess and neither can the compiler.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download