Function Declarations vs Expressions
What will this code output?
const x = 10;
function foo() {
console.log(x);
var x = 20;
}
foo();
This code will output `undefined`. This example demonstrates variable hoisting and shadowing within function scope. Even though there's a global `const x = 10`, inside the function `foo`, the local declaration `var x = 20` is hoisted. This means the variable declaration (but not its assignment) is moved to the top of the function scope. So within `foo`, the code behaves as if it were written: ```javascript function foo() { var x; // hoisted declaration, initially undefined console.log(x); // logs undefined x = 20; // assignment happens here } ``` The local `x` shadows (takes precedence over) the global `x`, so the global `x` is inaccessible within `foo` once a local `x` is declared. This is why `console.log(x)` outputs `undefined`—it's accessing the hoisted but not yet assigned local variable, not the global constant. This behavior is specific to `var`; if `let` or `const` were used instead, we would get a ReferenceError due to the temporal dead zone (accessing a variable before its declaration).