This question already has an answer here:
- Surprised that global variable has undefined value in JavaScript 4 answers
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 ?
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";
.