Expecting undefined in Javascript
javascript
Solution
JavaScript has function level scope, not block level scope.
The `var` statement is hoisted so your code is equivalent to:
function() {
var a;
if(true) {
a = 5;
}
alert(a);
}
If JavaScript had block level scope, then it still wouldn't output `undefined`. Since `a` would be undeclared in the `alert` statement, you would trigger a reference error.
Problem
I was seeing some Javascript code and I stumbled upon something like this: ``` function() { if(true) { var a = 5; } alert(a); } ``` I was pretty sure this would output undefined but it didn't ? Can someone tell me why?