Because func
is in essence:
function func(randomize) {
var x;
if (randomize) {
x = Math.random();
return x;
}
return x;
}
Variables in JavaScript have function scope, not block scope with which you might be familiar from other languages. This results in the hoisting behavior you observe:
What does happen is that variable and function declarations are put into memory during the compile phase, but stays exactly where you typed it in your coding.
...
JavaScript only hoists declarations, not initializations. (emphases mine)
That is, even though inside func
you declare x
in the if
block, during compile time its declaration is moved to function level where it shadows x
in global scope. However, it is only initialized if the argument to func
is true
which leads to the behavior you observe.
See also let
:
"use strict";
var x = 3;
function func(randomize) {
if (randomize) {
let x = Math.random();
return x;
}
return x;
}
console.log(func(false));
console.log(func(true));