Posted on December 27, 2018
Storing values that you can later reference is one of programmings most basic and fundamental concepts.
In JavaScript these named containers are called variables. Variables can be declared by using three different reserved keywords: var
, let
or const
.
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.
var exampleVariable; //declaration exampleVariable = 'test value'; //definition var exampleVariable = 'test value'; //shortened variation
Multiple variables can be declared in one statement:
//Creates three variables in one statement var variableOne = 'First', variableTwo = 'Second', variableThree = 'Third';
Variables can also be re-declared many times over by overriding them:
var example = 'test value'; // example holds the value - 'test value' example = 'new value'; //example now holds the value - 'new value'
let
(es2015)
let 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
, unlikevar
, does not create a property on the global object. let
variables are not initialised until their definition is evaluated. Therefore, unlikevar
,let
variables aren’t “hoisted” to the top of the block. Trying to access them will result in aRefrenceError
.- Variables declared using the
var
keyword are scoped to the immediate function body, whilelet
variables are scoped to the immediate enclosing block denoted by{ }
.
const
(ES6)
const 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:
const arr = ['Bob','John','William']; // console logging arr[1] returns 'Bob' // The method below reassigns 'Bob' to 'Mike' arr[1] = 'Mike'; // Console logging arr[1] returns 'Mike'