0
var x ="apple";

socket.on('fruits',function(data){
  var x = data;  //var x is orange here
});

console.log(x); /// but var x is still apple here.....


socket.on('DatatoServer',function(  
   socket.in(x).emit('receivedData', data); ///I want this x to be orange
});

how do I make that var x to become global variable?

or is there a way I can use that orange var x in my second socket.on listener above?

Any help is appreciated

The Reason
  • 7,705
  • 4
  • 24
  • 42
Tosps
  • 73
  • 7
  • Possible duplicate of [What is the scope of variables in JavaScript?](https://stackoverflow.com/questions/500431/what-is-the-scope-of-variables-in-javascript) – Jacob Thomas May 09 '19 at 19:54

1 Answers1

0

When you use the var keyword you are actually declaring a new variable x within the scope of your callback.

To reference x in the global scope, remove the var and set it directly.

Also, the fact that it's a callback might change the global scope, using an arrow function for your callback could resolve this.

socket.on('fruits', (data) => { 
    x = data; //var x is orange here
 }); 
jdavison
  • 322
  • 1
  • 9