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 declaration statement will cause the variable to act a little differently. Below is a brief explanation of those differences.
Basics
While there are a few technicalities to explore regarding the three declaration statements, we will begin by only covering the crucial differences:
- While
vardoes work, there is essentially no reason to use it anymore. Do not usevarin this course. - Use
constwhen the variable's value will not change after initialization. - Use
letwhen you plan on changing the variable's value after initialization.
var
NOTE
While the var declaration statement still works, it is considered "bad practice" to use. It is better to use let or const.
Just for your information. 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.
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.