JavaScript Variables

A variable is nothing more than a name given to a particular area in memory that stores a value created by JavaScript. In JavaScript, a variable has to be defined before it can be used and can store values such as numbers (123 or 45.67), strings ("Hello World"), or boolean values (True or False). When defining variables, its type does not need to be included in the definition, as a variable will take on the type of the value that is assigned to it. Below are some examples of how variables can be defined.

var name; // A variable that has been defined but not initialised.
var fname = "Bob"; // A defined and initialised variable.
var dob, gender, ethnicity; // Multiple variables defined but not initialised on one line.
var lastname = "Bloggs",
age = 30,
job = "Gardener"; // Multiple variables defined and initialised over multiple lines.

Variable Scope

The scope of a variable refers to the area of a script that it can be used. In JavaScript variables can be defined anywhere within a script and the scope can either be global or local.

A variable defined within a function is one that has local scope as it can only be referenced within the function it is defined.

function exampleFunction()
{
   var nationality = "English";
}

A variable defined outside of a function is said to have global scope and can be referenced anywhere within a script, even within a function.

var nationality = "English";
function exampleFunction()
{
   document.write(nationality);
}

exampleFunction();

In the above example, the value in the 'nationality' variable would still get output to the screen even though it was not defined within the function.

It is possible to define a global and local variable with the same name and each can store separate values. In this case, when executing code within a function where the local variable is defined, this would take precedence over the global variable.