The second example implements what is called a closure. The function bar is referencing the variable x from its surrounding context, i.e. the function foo. This precedes the reference to the global variable x.
See also this question Can you explain closures (as they relate to Python)?