Scope determines where a variable exists and does not exist in a program.

function bar ( ) { var foo = 2 ; console . log ( foo ) ; } bar ( ) ; console . log ( foo ) ;

Scope also determines which value to use when we have two different variables with the same name.

var foo = 1 ; function bar ( ) { var foo = 2 ; console . log ( 'foo inside bar: ' , foo ) ; } bar ( ) ; console . log ( 'foo outside bar: ' , foo )

If you run the example above, you will first see '2' logged to the console, and then you will see '1'. The foo created inside the bar function is a different variable from the foo created at the top of the program.

The foo variable declared at the top of the program is in the global scope. The foo variable declared inside the function is in that function's scope only. We say that the foo variable declared inside the function shadows the global variable.

What about function parameters? Do they shadow variables from a higher level scope?

var foo = 1 ; function bar ( foo ) { foo = foo + 2 ; console . log ( 'foo inside bar: ' , foo ) ; } bar ( 5 ) ; console . log ( 'foo outside bar: ' , foo ) ;

The fact that parameter names act like variables when it comes to scope and shadowing will be important in a future article on scope and closures.