Declaration Statements
There are three declaration statements in JavaScript: var, let, and const. To understand why there are three different declaration statements, we must look at the history of the JavaScript.
In 1995, when JavaScript was first created, it had only one declaration statement var
. For two decades it was the only way of declaring variables. But var
had limitations that some programmers, especially those who came from languages like Java, found annoying. So, in July 2015, the JavaScript version known as ES2015 or ES6 introduced two new declaration statement, let
and const
.
Each declaring statement will cause the variable to act a little differently. Below is a brief explanation of those differences.
var
The var
statement is used to declare a variable that has function scope or is accessible anywhere within a function. If declared outside of a function it will be given a global scope and be added to the global object. Variables declared with var
do not need to be assigned a value, can be re-assigned a value, and can be re-declared without an error.
NOTE
While the var
declaration statement still works, it is considered "bad practice" to use. It is better to use let
or const
.
let
The let
statement is used to declare a variable that has block scope or is accessible anywhere within a block or a set of curly braces. If declared outside of a function or block it will be given global scope but is NOT added to the global object. Variables declared with let
do not need to be assigned a value, can be re-assigned a value, but CANNOT be re-declared and will result in an error.
const
The const
statement is used to declare a variable that has block scope or is accessible anywhere within a block or a set of curly braces. If declared outside of a function or block it will be given global scope but is NOT added to the global object. Variables declared with const
MUST to be assigned a value, CANNOT be re-assigned a value, and CANNOT be re-declared. If any of these situations occur it will result in an error.
NOTE
Because const
forces a value to be set to any variable declared and prevents re-declaration, it is considered best practice to use const
in all cases, except when it is known that a variable value will change. Then use let
.