DEV Community

Todd Chaffee
Todd Chaffee

Posted on • Edited on • Originally published at blog.toddbiz.com

JavaScript and Scope I - Intro

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

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

bar();

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

Edit in JSFiddle

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

bar();

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

Edit in JSFiddle

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

Edit in JSFiddle

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.

Learn more about scope in JavaScript and Scope II - Functions

Top comments (0)