The output will be `undefined`. This example demonstrates variable shadowing and hoisting within function scopes. When the function `foo()` is called, it creates its own execution context. During the creation phase of this context, the variable declaration `var x;` is hoisted to the top of the function, creating a new variable `x` local to the function that shadows the global `x`. However, only the declaration is hoisted, not the initialization `x = 2`. So when `console.log(x)` executes, it refers to the local `x` which exists but is `undefined` at that point. The code effectively runs as:
```javascript
var x = 1; // global x
function foo() {
var x; // local x is hoisted, initialized as undefined
console.log(x); // logs undefined (local x, not global x)
x = 2; // local x is assigned 2
}
foo();
```
This behavior shows how function scopes create their own variable environments and how variable declarations within a function shadow variables with the same name from outer scopes.