When I use 'var', below function returns undefined.
var x = 3;
function func(randomize) {
if (randomize) {
var x = Math.random();
return x;
}
return x;
}
console.log(func(false)); // undefined
When I use 'let', the same function returns 3.
let x = 3;
function func(randomize) {
if (randomize) {
let x = Math.random();
return x;
}
return x;
}
console.log(func(false)); //3
How does compilation works here? Is this because of the lexical environment? I am surprised by the results. Please explain.