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
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.
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.
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
0here since you output this before the socket receives a messagex is unfortunately still: 5 // Yay! It updated (assuming the 'page' message is received after the 'key' message