Variables

What is a variable? 

A variable is a name given to a data value. Variables are identifiers which means when you choose a variable name, it must follow the identifier rules. The rules are:

  1. The first character must be an ASCII letter, underscore, or a dollar sign.
  2. There should not be a space or tab or newline in a variable
  3. The characters after the first can be either number digits or ASCII letters or underscore. Only one underscore between letters or numbers allowed.
  4. A variable name cannot be a keyword. Examples of keywords are: int, float, for, function, if, switch, var, while
  5. JavaScript is case sensitive which means a name with a capital letter is different from a name with a small letter:
      number is different from NUMBER

Variable Declaration
You can declare (introduce) a variable by writing the var keyword before the variable name. A value can then be assigned later.

Example: 

var numb      // declaration = creating or defining

Variable Declaration and Initialization:
JavaScript allows introducing a variable and immediately assigning a value. This is called initialization. In this case it is not necessary to use the var keyword.

Example: 

numb = 798  // initialization = assigning a value

var numb = 798 // declaration and initiation

Variable Typing:

Variables in JavaScript are untyped i.e. they can hold any data type.

Example:

The same variable is changed to hold a string after it previously held a number

numb = 3
numb = "three"

JavaScript automatically converts from one data type to another when needed.

Variable Scope:

Variable scope is where the variable is defined in the program. This restricts where the variable is used. You may think of scope as "where" the variable is visible. A variable defined inside a function is seen only within the block of that function i.e. inside the { } that follows the function name.

Variables declared outside functions are global variables; i.e. they are visible throughout the script region. All functions can use a global variable. Global variables are discourage because it is not easy to debug as it is not easy to know which function assigned a value to the variables. 
Variables declared inside functions are local variables; i.e. they are defined within that function only. A local variable of a function can only be used inside the function in which it is declared. 

Local variables take precedence over global variables with the same name.

Variable Scope Example


In the example reachable by clicking the link above, there are two functions called fn1 and fn2. Variable scope is declared outside both functions. Therefore, variable scope is global. It can be used in statements in both functions. The variable scope1 is declared inside the block of function fn1. Therefore, it is local to fn1 and cannot be used in fn2. Notice that another scope is defined in fn2. This second scope is local to fn2.