user3508612 user3508612 - 5 months ago 8
Node.js Question

Difference between the following nodejs codes

first code



net.createServer(function(socket){
socket.on('data',function(id){
getUserDetails(function(){console.log(id)});
});
});

function getUserDetails(next){
next();
}


Second Code



net.createServer(function(socket){
socket.on('data',function(id){
getUserDetails(function(){console.log(id)});
});
});

function getUserDetails(next){
console.log(id);
next();
}


The first code logs id where as the second code gives error. I understand that getUserDetails has no access to id but how come the callback passed to getUserDetails has access to id?

Answer

id is a variable scoped to the callback function of socket.on('data') event.

the getUserDetails method is not in that scope - therefore it can't access this variable.

The function you sent as a parameter to getUserDetails is declared inside the scope of the callback function where the id variable is in, so it can access it.

Comments