Variable Scope

Variables defined within a function are only accessible within that function. The following code will raise an error.

function nothing() {
  var y = 24;
  return(y);
}
nothing() // this works because the nothing() function can access the y variable
console.log(y) // this raises and error because the y variable cannot be accessed outside the nothing() function

The y variable is accessible within the nothing() function, but access to this variable is lost once the function is over.

By contrast, variables defined before the function are accessible within the function.

var greatBand = "Backstreet";
function important() {
  return(greatBand + " Boys");
}
console.log(important()); // "Backstreet Boys"

The greatBand variable is defined before the important() function and is accessible within the important() function.

The greatBand variable is still available after the function definition and invocation:

console.log(greatBand); // "Backstreet"

In summary, variables defined outside functions are accessible both inside and outside of functions. Variables that are defined within a function are only accessible within that function.

Question Click to View Answer

What does the following code print to the console?

var x = "sky";
function moon() {
  return("I live in the " + x);
}
console.log(moon());

I live in the sky

Because the variable x is defined outside a function, it is accessible anywhere — including inside any function (such as moon()). The variable x is accessible within the moon() function, so the expression `"I live in the " + x returns the string "I live in the sky".

What does the following code print to the console?

function pretty() {
  var look = "hipsters";
  return("I like " + look);
}
console.log(look);

This code raises an exception. The look variable is defined within the pretty() function and is only accessible within that function. The look variable exists only in the context of the pretty() function itself — console.log(pretty()) would still print "I like hipsters."

What does the following code print to the console?

var coolCat = "garfield";
function meow() {
  return(coolCat + " likes lasagna");
}
console.log(meow());
console.log(coolCat);

garfield likes lasagna garfield

The coolCat variable is assigned to the "garfield" string and can be used within the meow() function. The coolCat variable can also be used outside of the meow() function.

<-- Previous (Introduction to Functions) Next (Anonymous Functions) -->