1

I m a newbie to javascript. I usually program in Java. I am confused by this following code snippet.

<script>
 x = "foo";

function bar(p){
  if (p){
    document.writeln("x = " + x);
  } else {
    var x = "baz";
  }
}

bar("baz");

</script>

When I run the above code snipped its printing

 x = undefined

Why does it print undefined, since x is a global variable it should print foo right ? Can anyone explain ?

shbolise
  • 75
  • 3
  • 9

2 Answers2

1

since x is a global variable it should print foo right

It would if it wasn't shadowed by the var x = "baz"; declaration further up in your function; due to hoisting it will execute the function as if you wrote

function bar(p){
  var x; // = undefined

  if (p){
    document.writeln("x = " + x);
  } else {
    x = "baz";
  }
}

To make the code do what you want, you could simply write x = "baz"; instead of var x = "baz";.

Ja͢ck
  • 170,779
  • 38
  • 263
  • 309
0

try this output is x = foo

var x="foo";
function bar(p){

  if (p){
    document.writeln("x = " + x);
  } else {
    x = "baz";
  }
}

bar("baz");
Dexter
  • 1,804
  • 4
  • 24
  • 53