Variable Scope

When you declare a variable inside a function, it will be 'invisible' outside of the function. This means that only code that is inside the body of the function can use the variable. If you try to use the variable outside of the function, you'll find that the program will crash, and the error message in the console will mention that the variable has not been declared or defined.

function greetUser(userName){
  var greetings = "Hello, " + userName;
  alert(greetings);
}

alert(greetings); // you

The code sample above demonstrates that variables declared inside of functions are 'invisible' outside of the functions.

Interestingly, variables that are declared outside of any function can be used, or 'seen', from inside a function. Consider this example:

var salesTaxRate = 0.05;

function calculateTotalCost(price){
  var tax = price * salesTaxRate;
  return price + tax;  
}

Variables that are declared inside of functions are known as local variables. Variables that are declared outside of any function are called global variables. I'm not sure how the terms 'local' and 'global' came to be used, but here's my best metaphor to explain their origins: If you think of a function as a community of JavaScript code, then all of the commands inside the body of the function may be thought of as 'locals' who cannot leave the community (unless they are 'returned' by functions). On the other hand, global variables are available throughout the entire world (your entire program), and they can be freely used anywhere in the entire world, which makes them 'global'.

The visibility of a variable is known as its scope. A local variable is in scope only within it's enclosing function, and we often say that the variable is 'local' to that function. A global variable is in scope (visible) anywhere in your program.

You might be wondering why JavaScript is set up to work this way, for now don't worry about 'why'. At this point in your progress as a programmer, it's more important understand 'how' variable scope works because you'll avoid some mistakes (for example, a common mistake for beginners is to try to use a variable that is 'out of scope' (not visible). When you begin to study Java next semester, you'll see that this is useful feature.

Finally, it's important to know that global variables are truly global in your entire application. For example, if you declare a global variable in a .js file, it will be visible in other .js files that are linked to your program.

Let's create a few .js pages and link them to this page so that we can try it out!

Questions - JavaScript Variable Scope

Question 1

What is a 'local' variable?

Variables that are declared inside of functions.

Question 2

What is a 'global' variable?

Variable declare outside of a function.

Question 3

If you try to alert a variable that is not visible (not in scope), what will happen to your program?

It will not work.