JavaScript/Variables

Purpose
Computer languages need to use variables. Why this? In most cases, programs don't solve single problems like the very concrete question: What is the circumference of a circle with a radius of 5 cm? Such a concrete question can be solved without using variables:  Instead, most questions are more general: What is the circumference of a circle with an arbitrary radius? You don't want to write a program for a radius of 5 cm, another program for a radius of 6 cm, another one for a radius of 7 cm, and so on. You want to write a single program that computes the circumference for all possible radii. The program needs input (from a user, from another program, from a database, ...) that tells him for which value it shall run. , or even better:.

Those two examples are flexible. They ask the user for the desired radius, store the given value in a variable with the name r, and compute the circumference using this variable. The variable r is introduced by the keyword. And there is a second variable. The module Math has predefined a variable PI with the keyword :.

In JavaScript, variables can be used similarly to variables in mathematical formulas. During runtime, the values of variables are stored in the main memory of the computer (RAM), from where they can be used at a later moment in the lifetime of the program. You can imagine a variable as a small box where you deposit some value and take it out whenever you need it.

Variables are a cornerstone in the transition from individual problem solving to a strategy, respectively an algorithm.

Declaration and initialization
If you want to use a variable, we recommend declaring them explicitly. This is not mandatory but has strong benefits.

In many cases, the declaration is accompanied by an initialization, e.g. . The declaration is , and the initialization is. But it's also possible to omit the initialization part:  which causes the value of the variable to be.

Keyword
The keyword  introduces a variable whose value may be changed multiple times.

Keyword
The keyword  introduces a variable that must be initialized immediately. Moreover, this very first value can never be changed. That helps the JavaScript engine to optimize the code for better performance. Use  as often as possible.

When you work with objects, e.g., with arrays, in combination with the keyword, it's the same: you cannot assign another value (object, array, number, or whatever) to the variable. Nevertheless, its elements can be changed.

In some cases  variables are written in uppercase, e.g.,. This is a convention and not mandatory.

Keyword
At first glance,  is identical to. But the range where such variables are known is different from the variables declared by ; see chapter Scope below.

Omitting the declaration
You can assign a value to a variable without declaring the variable previously. "JavaScript used to allow assigning to undeclared variables, which creates an undeclared global variable. This is an error in strict mode and should be avoided altogether." In other words: The variable goes to global scope, see below. As long as you don't have good reasons you should avoid using the global scope because its usage tends to create unwanted side effects.

Sometimes such situations occur by accident. If there is a typing error in the source code, JavaScript uses two different variables: the original one and a new one with the wrongly typed name - even if you use one of the keywords,  , or.

You can instruct JavaScript to search for such typos by inserting the command  as the first line of your scripts.

Data types
Programmers who are familiar with (strict) typed languages like Java may miss in the above chapter the possibility of defining the type of variables. JavaScript knows many different data types. But their handling and behavior is very different from that in Java. In the next chapter you will learn about that.

Scope
A scope is a range of consecutive JavaScript statements with a clearly defined start and end. JavaScript knows four types of scopes: block, function, module, and global scope. Depending on the kind of declaration and the location of the declaration, variables are within such scopes. They are 'visible' respectively 'accessible' only within their scope. If you try to access them from outside, an error will occur.

Block scope
A pair of curly brackets  creates a block. Variables declared within a block by  or   are bound to this block and cannot be accessed outside.

The variable  is declared inside a block (in this simple example, the block consists of only two lines.) It is not accessible behind the end of the block, which is the closing curly bracket   in the   line. The same applies to the case that the variable  is declared with   instead of.

Be careful with the keyword ; its semantics is different! First,  is not block-scoped. Second, it leads to a technique called hoisting, which has been used in JavaScript since its first days. Hoisting changes the semantics of different declarations 'under the hood'. Concerning, it splits declaration and initialization into two separate statements and shifts the declaration part to the top of the current scope. Hence the variable is declared but not initialized if you use it before the line where it is declared in the source.

The script

is changed to:

On the other hand, the keyword  keeps the declaration in the line where it is written.

There are more differences. Here is a version of the first example of this chapter replacing  by  :

We recommend avoiding  completely because of two reasons: Instead of using, use the keyword.
 * JavaScript's hoisting technique is not easy to understand.
 * Other members of the C-family languages don't know it.

Function scope
A function creates its own scope. Variables declared in the function's scope cannot be accessed from outside.

The function scope is sometimes called the local scope because this was the name in older ECMAScript versions.

See also: Closures works the other way round - access of outer variables inside the function.

Module scope
It is possible to divide huge scripts into multiple files and let the functions and variables communicate with each other. Each file creates its own scope, the module scope. The chapter JavaScript/Modules explains more about that.

Global scope
Variables or functions are in global scope if they are declared at the top level of a script (outside of all blocks and functions).

is declared at the top level, hence it is in the global scope and can be used everywhere. But in the next example the declaration of  is wrapped by. Hence it is no longer in global scope.

Hint: The use of the global scope isn't considered good practice. It tends to create unwanted side effects. Instead, try to modularize your code and let the parts communicate via interfaces.

Exercises

 * ... are available on another page (click here).