Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Understand the scope of the variables in Node.js

Understand the scope of the variables in Node.js

Problem

I have the follow NODE.JS code:

var a = [1,2,3,4,5,6]

function test(){

  var v = a.pop()
  if (!v) return

  function uno(){    
    due(v, function(){
      console.log(v)      
    }) 
    console.log("Start:",v)              
    return test()
  }

  function due(v, cb){      
    setTimeout(function(){ 
      console.log(v);
      cb(); 
    }, 5000);    
  }   
  uno();
}  
test()

This is the output:

Start: 6
Start: 5
Start: 4
Start: 3
Start: 2
Start: 1
6
6
5
5
4
4
3
3
2
2
1
1

as you can see inside uno() function i call due() function with a timeout.

I have two: console.log(v) (inside uno() and due())

could somone explain me WHY when i call the callback (cb()) the v value is the same?

doing:

due(v, function(){
  console.log(v)      
}) 

the console.log will keep the v value i passed in the due() call? Why it does not get the "global" v value on the test() function?

Problem courtesy of: Dail

Solution

The callback cb() is the following function: function(){ console.log(v) } and the v is taken from the local environment that is in effect when you define the function, because it is not a parameter to the callback function (upvalue). That means, the first time you call test(), it has the value 6, the second time the value 5 etc.

You should give the parameters different name than the global variables, for example:

  function due(param_v, cb){      
    setTimeout(function(){ 
      console.log(param_v);
      cb(); 
    }, 500);    
  }   

Then you might spot the difference.

Edit: this is not related to node at all, more to JavaScript (and many programming languages behave exactly the same). You should play around with it and put the callbacks etc. aside for a while.

var a

function print_a () {
  // this function sees the variable named a in the "upper" scope, because
  // none is defined here. 
  console.log(a) 
}

function print_b () {
  // there is no variable named "b" in the upper scope and none defined here,
  // so this gives an error
  console.log(b)
}

a = 1

print_a() // prints 1
// print_b() // error - b is not defined

var c = 1

function dummy () {
  var c = 99
  function print_c () {
    // the definition of c where c is 99 hides the def where c is 1
    console.log(c)
  }
  print_c()
}


dummy() // prints 99
Solution courtesy of: topskip

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Understand the scope of the variables in Node.js

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×