Scope It Out - JavaScript Variable Scope

You know what a function is and you know how to create variables. Did you know that a variable behaves differently when it is used inside a function? Specifically, we are talking about variable scope. No, not the mouthwash for variables, although sometimes I feel like my variables could use a good cleaning. We are talking about the scope, as in the range of the effect of a variable.

Javascript training classes in Los Angeles.

What do we mean by this? There are two types of variables when we are discussing scope, global and local. A global variable's value is accessible by the entire program, no matter where the variable is called or assigned. Global variables can be accessed inside of functions as well as outside. On the other hand, local variables can only be accessed by the functions that created them, where they are declared.

Variable declaration is the key here so let's be clear on what we mean. You declare a variable when the variable name is following the "var" method:

This would create (declare) a variable with the name "firstName" without a value, or the value of null.

var firstName;

This would declare the same variable but this time assign it with the string value of "Jeff".

var firstName = 'Jeff';

You could also create the same variable without the "var" method.

firstName = 'Jeff';

Whether you use the "var" method or not isn't just a matter of convenience, although some developers thought that JavaScript just didn't care and was sticking true to the nature of a loosely coded language. There are actual differences in how JavaScript is creating the variable depending on whether the "var" method is used.

When the "var" method is used the variable is treated differently depending on where the variable was created. If the variable was created outside of a function in the main script, then the variable is created as a global variable. Remember what we said about global variables? They can be accessed from anywhere inside the script.

If a variable is created using the "var" method inside a function, then it is created as a local variable that is accessible by that function only. The variable's value cannot be accessed outside the function.

Look at this example:

When we call the 'firstName' variable inside the function to combine it with 'lastName' to create the value for 'fullName', the function can use it because it was created outside the function [line 1] and is therefore global. The function can print 'fullName' because it was created inside the function [line 5]. But when we try to access the 'fullName' variable outside the function we get an invalid object error. The main script cannot see the 'fullName' variable because it is local to the function that created it, the "createName" function in this case. Notice, I had to write the string '<br>From Outside: ' in a seperate statement because the 'fullName' variable is not recognized and that statment fails. If I had concatenated the string and the variable on in the same statement, the whole statement would fail and we would get no output from those statements.

Take a look at a different variation of that script:

The difference is we created the "fullName" variable using the "var" method on line 2 without a value. Within the function we assigned it a value by concatenating the variables "firstName" and "lastName" with a space in between just like the example above but, this time the variable was not created within the function so it is a global variable and accessible by the entire script, both inside and outside the function.

There is one other nuance regarding variable declaration that we need to understand.

Again, a slight change in our script. Here we don't declare the "fullName" variable on line 2 and we don't use the "var" method inside the function. Both write statements still have access to the variable because when we don't use the "var" method to declare a variable, JavaScript treats it as a global variable regardless of where is was created.

This is an important distinction to understand. It's not that JavaScript is such a loosely coded language that it didn't care whether the "var" method was used or not, but JavaScript is treating the creation of the variable differently.

I have seen a lot of code that was created without using the "var" method at all, seeming to indicate that the method was irrelevant and could be left out without consequences. As you can see by our examples, this is not true, and we can end up with some unexpected results when we use, or don't use, the "var" method correctly.

Because it is always beneficial to create code that is clear and precise to the developers reading the code, we should not be creating variables without using the "var" method. It is better practice to declare our variables that we want to be global at the top of the code, and declare our variables that we want to be local to a function at the top of the function. Although it requires a little more code to do this, our intention is immediately clear.

In the previous example it is clear that our intention is for the "firstName" and "fullName" variables to be global because they are declared outside the function [line 1 and 2] and the "lastName" variable is meant to be local because it is declared inside the function at the top.

The benefit of using local variables inside our functions is to reduce the number of variable names we have to maintain. We can reuse variables names that are just meant to temporarily store a value while the function runs.

We can use the variable "text" in multiple functions without worrying about the values sticking around from one function to the next. If all variables were global we would have to create a different variable name for each function that needed a temporary place to store values, i.e. text1, text2, text3, text4, etc. That not only creates more variables for us to track but also takes more space in memory for each new variable.

Understanding and using global and local variables correctly will create much more efficient code and help the developer to quickly understand the intended use of the variable. If you would like to learn more about using variables and the JavaScript language visit JavaScript Training Courses on our website for some excellent classes on the subject.


Onsite JavaScript training

Through our network of local trainers we deliver onsite JavaScript classes right across the country. Obtain a quote for onsite JavaScript training.

To view a sample of our past students testimonials, please click on the following link: Javascript testimonials.