JavaScript variable declarations
differentiating const + let + var when declaring variables
// updated 2025-05-02 12:00
In computer programming, to declare a variable simply means to initialize it with a name and, optionally, a value.
The keywords const
and let
We use the keywords const
and let
to declare what kind of statement that we wish to make:
const
is a variable but up until the point we declare it- we can change its value at its line of declaration
- but we cannot re-assign it at any other point in the program
- we can change its value at its line of declaration
let
is a variable in its truest form- we can change its value after its declaration
- at any other point in the program
- we can change its value after its declaration
// we can change "100" here...
const x = 100
// ...but we cannot change it here
x = 200
// we can change "100" here...
let y = 100
// ...and we can change it here because of let
y = 200
The var
keyword
There also exists another keyword var
which is similar to let
but:
let
has block scope- i.e. it exists only within the confines of its closest curly braces
var
has function scope and global scope- if declared inside a function, it exists only within the confines of its parent function
- if declared outside a function, it will have global scope
- the same variable can also be re-declared
- has no block scoping
function doSomething() {
// function scope for var
const x = 10
if (x > 0) {
// block scope for let
let z = 100
z = 200 // we can change it here
var t = 1
}
// "1" (this call exists inside the function scope)
console.log(t)
// undefined (this call exists outside the block scope)
console.log(z)
}
The var
keyword has largely phased out, in favour of both let
and const
but it still remains important to know when working with old JavaScript code!
Reserved keywords
When we declare variables, we cannot use some reserved keywords as variable names, e.g.:
let let = 1
...won't work because the language won't let us use the second let
as a variable name! This tries to make our code less confusing!
For a full list of reserved keywords, we have this w3schools page!