Understanding JavaScript Variables

The variable is one of the most fundamental concepts in any programming language. The first step towards becoming proficient in JavaScript is having a good understanding of variables.

Variables can be a little confusing, especially to newbie programmers. Even people who are familiar with variables from other programming languages may find JavaScript’s take a little strange. The good news is that JavaScript variables are actually easy to understand.

This tutorial is going to help you achieve just that. We shall start from the basics, and progress to the trickier parts.

Let’s start from the very beginning:

What Is A Variable?

A variable is a way to store information so that you can later use it. What does this mean? To answer this question, let us use an illustration:

Consider the following JavaScript statement:

alert ('Hi Alex, Pleased to meet you');

This will of course pop an alert box with the phrase ‘Hi Alex, Pleased to meet you’. Now, this can be wonderful if Alex visits the page. But what if someone else visited the web page? You wouldn’t want to offend them by calling them Alex, would you?

You can make things simpler by asking for the visitor’s first name, and then offering them a customized greeting. The JavaScript prompt() function can easily give you the name. The statement,

	prompt('What is your first name?');

will easily get you the name. But that throws you in a dilemma; how do you store the visitor’s name? The answer is simple, using a variable. Let us call the variable “first_name”. We can store the visitor’s name as follows

	var first_name = prompt('What is your first name?');

Don’t mind if you don’t understand the “var first_name =” part of the above statement. You’ll understand it shortly. The point here is that we are storing the visitor’s name in a variable called “first_name”. So, now that we have the name, we can give them a customized greeting:

	alert ('Hi ' + first_name + ', Pleased to meet you');

This now gives a customized greeting. You can try it by clicking the button labeled “Check It Out” below. You can try it several times with different names.

Now that you’ve seen a variable in action, let’s go back to our definition:

“A variable is a way to store information so that you can later use it.”

In our example, the information was the name of the visitor. When we wanted to store it, did so in a variable.

var first_name = prompt('What is your first name');

And how did we use the information? Well, we added it to the text in the alert box:

alert ('Hi ' + first_name + ', Pleased to meet you');

We could have used it in other ways. For example, we could have displayed it alone in an alert box

	alert(first_name);

Or written it to the page:

document.write(first_name);

The bottom line is that a variable provides a way to store information. Once you have stored the info, you can use in any way you want. You will see more examples of how to use variables as this tutorials progresses.

Anyhow, since you now know what a variable is used for, let us proceed to how to create variables:

Declaring A Variable

Before you can use a variable, you have to create it. In programming-speak, creating a variable is called “declaring a variable”. In JavaScript, you create a variable using a two step process.

  1. Find a name for your variable
  2. Transform that name into a variable

Let’s look at each of these steps in detail

1. Finding a Name

Before you can create a variable, you have to make up a name for it. In our example, we came up with “first_name”. But we could have given anything else like “_name”, “mammoth”, “x” or even something nonsensical like “zxsye”.

Basically, you can call your variable whatever you like – as long as you can remember it. However, it is often advisable to give a name which is easily recognizable. A simple rule of thumb is to use a name which is descriptive of what you intend to store in the variable. We called ours “first_name” which is descriptive enough. Another option could have been “firstName”.

We’ll return to the issue of names later. For now, just know that before you can create a variable, you need to find a name for it.

2. Transform the name into a variable

Once you have a name, you need to make it a variable. In JavaScript, you do this by placing the keyword “var” to the left of the name as follows:

	var first_name;

The “var” keyword is used to create a variable (or declare a variable). As long as you place “var” to the left of any word, that word automatically becomes a variable. For instance,

	var summer;

creates a variable called “summer”,

	var interest;

creates a variable called “interest” and so on.

However, a variable name can’t be any arbitrary word or sequence of characters. JavaScript provides a set of rules for creating variable names. For a variable name to be valid, it should conform to these rules.

Creating A Valid Variable Name

If the name you select isn’t valid, there will be a JavaScript error, and your script will not run.

    • A variable name can contain letters, numbers, underscore(_), dollar sign ($). These are some valid names: “first_name”, “$mart”, “data23” but these are invalid “@erica”, “&mart” and “first%name”
    • A variable name must begin with a letter, an underscore (_) or a dollar sign($). A variable name cannot begin with a number. “$mart”, “_week_day” and “f8” are valid while “7up”, “1zone” and “8_mile” are invalid.
    • A variable name cannot be a keyword. JavaScript keywords like “if”, “else”, “switch”, “function” and so on cannot be used as variable names.

Plus, future keywords like class, const, enum etc also can’t be used as variable names.

    • Many non-english, unicode characters can be used in Javascript variable names

For example, ʘʘ is a valid Javascript variable name!

I know it is difficult to remeber all those complicated rules. Here is a simple tool to generate/validate a Javascript variable name:

A variable name is case sensitive. “first_name”, “First_name”, “First_NAME” and “FIRST_NAME” all refer to different variables

More about valid Javascript variable names

The Scope of A Variable

The scope of a variable is the context in which the variable can be accessed. You can only access a variable from within its scope.

These are global variables and local variables. These variables are distinguished by where they are defined, and how wide their scope is.

A global variable is defined outside a function. And it is accessible from anywhere within a script, including inside functions. For example:

var number = 12;
function squareNumber()
{
    number = number * number;
}
alert(number);  // displays 12 in the alert box;
squareNumber();
alert(number);  // displays 144 in the alert box;

In the above example, the variable “number” is a global variable. It is declared outside a function. However, its value is changed from within the function squareNumber(). This is because the function has access to it. It is then called in alert() functions, which are outside squareNumber(). A global variable is accessible from anywhere within your script.

A local variable is declared within a function. It is only accessible within a function in which it was defined. You cannot access a local variable from outside the function where it has been defined. For example:

function showTheSquareOf (number)
{
    var square = number * number;
    alert('The square of ' + number + ' is ' + square);
}

The variable “square” is a local variable. It is defined within the function showTheSquareOf(). It can only be accessed within this function. Its scope ranges from the opening brace { to the closing brace } of the function. The alert() function can access it because it is within the scope.
showTheSquareOf(7);
will display an alert box with the words: “The square of 7 is 49”.

However, any statement outside the function showTheSquareOf() cannot access the variable called “square”. For instance, if we have the following statements:

showTheSquareOf(6);   //displays an alert box with the words: "The square of 6 is 36".
alert(square);  // throws a JavaScript error: "square is not defined".

The second alert will not display at all. However, if you go to the JavaScript console, you will find something like “Uncaught ReferenceError: square is not defined”

The reason is simple. “square” was defined within the function showTheSquareOf(). And it is only accessible within that function. To any statement outside the function, it is as well as not defined.

Arguments/Parameters

What about the word “number” which appears between the parenthesis of the function showTheSquare() and within the function itself? As in:

function showTheSquareOf (number)
{
    var square = number * number;
    alert('The square of ' + number + ' is ' + square);
}

“number” is actually a special type of variable called an argument (or parameter). An argument is used to pass on values into the function.

showTheSquareOf(5);   //displays an alert box with the words: "The square of 5 is 25".
showTheSquareOf(6);   //displays an alert box with the words: "The square of 6 is 36".

Arguments are actually local variables. Their scope is limited within the function.

More On Global Variables

We earlier mentioned that a variable declared within a function becomes a local variable. And its scope is limited to that function.
You can create a variable within a function, and its scope can extend beyond the function. In essence, you can create a global variable from within a function.

To do this, you simply skip declaring the variable (using the “var” keyword) and assign a value to the variable.

For instance, let’s rewrite our showTheSquareOf() function, and eliminate the keyword “var” from the declaration of the variable “square”

function showTheSquareOf (number)
{
    square = number * number;
    alert('The square of ' + number + ' is ' + square);
}

Now, if we have the following code:

showTheSquareOf(6);   //displays an alert box with the words: "The square of 6 is 36".
alert(square);  // displays an alert box with the number 36.

Note how the variable square suddenly became global variable. Now this may seem like a good idea. But it actually isn’t. It can lead to potential bugs which are difficult to trace. global variables will “pollute” the name space. There can be other scripts that are using the same name and they may update the variable at different places. This leads to unpredictable behavior. So it is better to keep the scope of the variable to a limited area (like a function , class etc).

Variable Hoisting

We earlier mentioned that the first step of creating a variable is declaring it. In essence, we said that you cannot use a variable you haven’t declared. Well, this actually isn’t true. You can actually assign a value to a variable, and then declare it later. For instance

x = 7;
alert(x);  // displays an alert box with the number 7
var x; 

The above code works perfectly well. Despite the fact that the declaration is in the last line, the alert box still displays the correct value stored in x. In fact, the above code snippet is the same as writing

var x;
x = 7;
alert(x);  // displays an alert box with the number 7

This rather peculiar behavior is called variable hoisting. It enables you to use variables and then declare them later. It works because of how the JavaScript interpreter operates. Before beginning to execute your code, the all declarations are moved to the top of the context. All global variable declarations are moved to the top of the script. And all local declarations are moved to the top of the function. Therefore, irrespective of where a declaration is placed, it gets executed before the other code in that context.

However, it is important to note that hoisting only works with variable declarations, not initialization. If we are to rewrite this code

x = 7;
alert(x);  // displays an alert box with the number 7
var x;

And use an initialization statement as:

alert(x);  // displays error message: "Uncaught ReferenceError: x is not defined"
var x = 7;

The error message is of course displayed in the JavaScript console. On the page, the script will not generate an alert box. The point here is that hoisting only works with variable declarations. Variable initializations aren’t moved to the top of the scope.

Hoisting is certainly an interesting and useful feature. However, unless you have a very strong reason to use it, please refrain from it. To make your code organized, easy-to-read, and easy to debug, declare all your variables before you use them.

Checking Whether A Variable Is Defined

During the course of this tutorial, we have seen several instances where undefined variables have led to errors like: “Uncaught ReferenceError: x is not defined”. This can be an inconvenience. The worst part is that the error message is actually displayed in the JavaScript console. If you don’t know where to find the console, it can be frustrating.

The easiest way to alleviate this frustration is to check whether a variable has been defined before you use it. You can check this using the JavaScript property called “undefined”. This property is used to describe any variable which hasn’t yet been defined.

You can check for the status of any variable using an “if statement”. Let’s say you have a variable called “first_name”, you can check for its status as follows

if(first_name === undefined) 

or

if(typeof first_name === undefined)

Both these statements will return true if first_name is not defined. In an actual programming scenario, you can ensure that the code below is run only when first_name has actually been defined:

if(first_name !== undefined)
{
alert ('Hi ' + first_name + ', Pleased to meet you');
}

The bottom line is that you can use the “undefined” property to eliminate the errors which can arise when you attempt to process an undefined variable.

Be Sociable, Share!

Comments on this entry are closed.