2

Really basic javascript question:

Global variables in javascript and node.js, what am I doing wrong? I've seen other posts where the answer was to return the value at the end of the function. I tried this and I still can't get the value to be altered to "5" and stay that way throughout my socket connection. Any help would be greatly appreciated!

Could it be the fact that the variable is changed in an anonymous function?

var x;

io.sockets.on('connection', function(socket){
    x = 0;
    console.log("x at first is: " + x);
    socket.on('key', function(value){//value = 5
          x = value;
          console.log("x is now + " + value);
          return x;
    })

    console.log("outside, x is " + x);

    socket.on('page', function(){
          console.log("x is unfortunately still: " + x);
    })
})

and my console log looks like this:

x at first is 0

x is now 5

outside, x is 0

x is unfortunately still: 0

3 Answers 3

1

That is because in console.log("outside, x is " + x) x is does not actually get set due to function scope. Try:

console.log("outside, x is " + socket);

Since x is return in your socket function.

Sign up to request clarification or add additional context in comments.

Comments

1

You create new function scoped variable x with following statement: var x = value; In the function it overrides your global variable. Remove you "var" and only set x = value to access the global variable.

Comments

1

You've used the var keyword when you assign a new value to x, which makes that x local to the anonymous function you declare it in. It is not the same x as you have outside that function. Delete that var keyword and you'll get:

x at first is 0

x is now 5

outside, x is 0 // You should expect 0 here since you output this before the socket receives a message

x is unfortunately still: 5 // Yay! It updated (assuming the 'page' message is received after the 'key' message

1 Comment

That was actually a typo on my part, the output is still the same without var being declared inside the socket.on('key') function. Any understanding of what might be going on in that case?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.