var
variables are function-scoped, so the expectation that a var
variable should not be known outside its functional scope is correct.
The mistake in your reasoning is that you think that if
and else
are functions and consequently you think that a var
variable created in an if
or else
block should not be seen outside them.
But if
and else
are not functions. if
and else
are conditional statements, so they are not functions. test
in your code is a function. Let me illustrate this for you:
function test(param) {
if (param === 1) {
var myVar = 1;
let myLet = 1;
const myConst = 1;
console.log({
myVar: typeof myVar,
myLet: typeof myLet,
myConst: typeof myConst
});
} else {
var myVar = param;
let myLet = param;
const myConst = param;
console.log({
myVar: typeof myVar,
myLet: typeof myLet,
myConst: typeof myConst
});
}
console.log({
myVar: typeof myVar,
myLet: typeof myLet,
myConst: typeof myConst
});
}
test(Math.floor(Math.random() * 2));
console.log({
myVar: typeof myVar,
myLet: typeof myLet,
myConst: typeof myConst
});
First, we check whether the var
, the let
and the const
are seen inside their block's scope, then we check for the same inside their function's scope, but outside their block's scope and finally we do the same check outside their function's scope.
You might also want to check this article's Block Scope section.