Posted on December 27, 2018
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.
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 variableName = 'variable value';
Introduced in ES2015,
let encourages the philosophy that variables should only exist where they are needed.
let variables can be reassigned at any point in the program but three main differences exist:
- At the top level,
var, does not create a property on the global object.
letvariables are not initialised until their definition is evaluated. Therefore, unlike
letvariables aren’t “hoisted” to the top of the block. Trying to access them will result in a
- Variables declared using the
varkeyword are scoped to the immediate function body, while
letvariables are scoped to the immediate enclosing block denoted by
const variableName = 'variable value';
Introduced in ES6,
const also allows you to define a new variable.
const has block scope but one fundamental difference exists.
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 returns 'Bob' // The method below reassigns 'Bob' to 'Mike' arr = 'Mike'; // Console logging arr returns 'Mike'