-3
 function setx(){
    var x = 'foobary bazer'
    showit();
 }

 function showit(){
   console.log(x);
 }

 setx();

In the above example, the showit function fails because x is undefined. However, x is set and is available in memory (or so I thought) before showit is called. Why is this not the case?

Also, what's the best way to make this code work, so the console.log does indeed print foobary bazer to the console? I could get rid of the var and make it a global, but I don't think this is the best way as it can cause strange bugs.

Starkers
  • 10,273
  • 21
  • 95
  • 158

1 Answers1

0

You could pass the x variable to the showit function:

function setx(){
    var x = 'foobary bazer'
    showit(x);
}

function showit(x){
    console.log(x);
}

setx();
Boomstein
  • 161
  • 2