Odd Café

JavaScript and Scope I - Intro

June 1, 2019 • 1 min read

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

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

bar();

console.log(foo); // ReferenceError: foo is not defined;

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); // logs 2
}

bar();

console.log('foo outside bar: ', foo) // logs 1;

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); // logs 7
}

bar(5);

console.log('foo outside bar: ', foo); // logs 1

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.