Variables and Constants

Declaring Variables

Local variables are declared using the var keyword. Global variables, which can not be used in strict mode, are declared by omitting the keyword var. Variables should always be initialized when they are declared.

Variables are loosely typed so can hold any value.  For example we can change the type of value stored in a single variable.

var message = “hi”; // message holds the string “hi” 
message = 100;      // now message holds the integer 100

Multiple variables can be defined in a single statement.  This practice, however, is discouraged because it results in hard to read and debug code.

var message = “Hi”, found = false, age = 20;   // not preferred

var message = "Hi";       // preferred
var found = false;
var age = 20;

A block of code is define by curly braces { }.  A variable defined with var has script-scope if it is defined outside a function and has function-scope if it is defined inside a function.  That is a variable declared with var outside a function (even within a block) is in scope anywhere in the script.  And a variable defined with var inside a function (even within a block) is in scope anywhere in the function.  This behavior is called hoisting.  A variable that is referenced before it is declared will have a value of undefined.

console.log(i);       // prints undefined
if (true) {
    var i = 10;
}
console.log(i);       // prints 10

If, however, you attempt to use a variable that is not declared within a scope, a ReferenceError will occur.

console.log(x);   // ReferenceError: x is not defined

Variables Declared With let

Variables can also be declared with the let keyword.  A variable declared with let is in scope only within the block in which it is defined.  Using the example above, if we declare the variable i with let, it is an error to use it outside the if block.

console.log(i);   // ReferenceError: i is not defined
if (true) { 
    let i = 10; 
} 
console.log(i);   // ReferenceError: i is not defined

Constants

A constant can be declared using the const keyword.  Constants are immutable.  As such it is an error to attempt to change their value after they have been initialized.  Constants have the same scope as variables declared with let.

const x = 10;
x = 5;            // TypeError: Assignment to constant variable.