Var, Let & Const
Storing values that you can later reference is one of programmings most basic and fundamental concepts.
Each way differs in how you can interact with the variable later on but all are refereed to as “untyped”. This means they do not have any type attached, allowing for any type to be assigned.
The example below shows you how to declare a variable and then define the variable by giving it a value.
Note: A variable must always be declared before you can use it.
1var exampleVariable; // declaration2exampleVariable = 'test value'; // definition3var exampleVariable = 'test value'; // shortened variation
Multiple variables can be declared in one statement:
1// Creates three variables in one statement2var variableOne = 'First',3variableTwo = 'Second',4variableThree = 'Third';
Variables can also be re-declared many times over by overriding them:
1var example = 'test value';2// example holds the value - 'test value'3example = 'new value';4// example now holds the value - 'new value'
1let variableName = 'variable value';
Introduced in ES2015, let encourages the philosophy that variables should only exist where they are needed.
Just like var, let variables can be reassigned at any point in the program but three main differences exist:
- At the top level, let , unlike var , does not create a property on the global object.
- let variables are not initialised until their definition is evaluated. Therefore, unlike var, let variables aren't "hoisted" to the top of the block. Trying to access them will result in a RefrenceError.
- Variables declared using the var keyword are scoped to the immediate function body, while let variables are scoped to the immediate enclosing block denoted by .
1const variableName = 'variable value';
Introduced in ES6, const also allows you to define a new variable.
Just like let, const has block scope but one fundamental difference exists.
Once a const variable is initialised, its value can not be changed unless it’s part of an object that provides methods that mutate its content. For example, an array:
1const arr = ['Bob','John','William'];2// console logging arr returns 'Bob'3// The method below reassigns 'Bob' to 'Mike'4arr = 'Mike';5// Console logging arr returns 'Mike'