user3508612
user3508612

Reputation: 77

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?

Upvotes: 1

Views: 48

Answers (1)

gibson
gibson

Reputation: 1086

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.

Upvotes: 1

Related Questions