Variable Declaration in JavaScript: var, let or const?
November 16, 2018
There are 4 ways of variable declaration in JavaScript. Beginner web developers are usuallly confused about the effects of different ways.
Hence, this article is for beginners to understand the differences among the 4 ways of declaring variables in JavaScript and when to use them.
Fly to the conclusion if you can’t wait =.=
Let’s go through them
1. “Freestyle” Way (Yes, it works, but is strongly NOT recommanded!)
myVariable = 'abc';
It’s possible that you declare a variable in JavaScript without using any keyword var
, let
, const
. It simply means that you have created a global variable.
In node environment, let’s run the following code snippet
a = "test";
console.log(a);
// output: test
The result shows test
, which means it works!
However, if we add 'use strict'
to enter strict mode, such declaration method is prohibited
"use strict";
a = "test";
console.log(a); // ReferenceError: a is not defined
An error is thrown. ReferenceError: a is not defined
This method is highly NOT recommanded because it is prohibited under strict mode and it will pollute your global environment. If your global environment contains too many useless temporary variables, your program will likely go into unpredicted errors and it will be a horrible experience to debug on such problem.
So, DO NOT use this way at all.
2. var
var
is the most common way of declaring a variable in JavaScript. Before ES6 was released, you should always use var
to declare your variables.
However, var
also has its limitations because the variables declared with var
is at function level.
What does it mean? See the following example.
"use strict";
function test() {
for (var i = 0; i < 10; i++) {
var count = i;
}
console.log(count);
}
test();
// Output: 9
Before running this piece of code, what do you expect the output of the function to be? Throwing an error? You might probably think that count
is declared within the for loop, it should not be accessible outside of the loop.
But sorry, if you use var
to declare a variable, the variable belongs to the function scope, which means that even though count
is declared within the for loop, count
still belongs to test()
function. Hence, as long as it’s within test()
function, count
is accessbile!
Another evidence is that, no error is thrown at all even if you console.log(count)
before declaring it within a function! Since no error is thrown, it would be hard to trace when unexpected bug occurs.
"use strict";
function test() {
console.log(count); // runs before declaration
for (var i = 0; i < 10; i++) {
var count = i;
}
}
test();
// Output: undefined
The output shows undefined
instead of throwing errors! Instead, errors will be thrown if the count
is not declared at all!
"use strict";
function test() {
console.log(count); // error is thrown
}
test();
3. let
let
is introduced in ES6. It is scoped at block level, which resolves the difficulty you might encounter when using var
.
By using let
, the following code snippet correctly throws errors ReferenceError: count is not defined
"use strict";
function test() {
for (let i = 0; i < 10; i++) {
let count = i;
}
console.log(count); // ReferenceError: count is not defined
}
test();
That is because let
makes count
variable become block-scoped. count
only exists in this for loop. It is a better way to use when declaring variables.
However, it also has its disadvantage. let
is not compatible with old browsers such as IE 11. If you are writing JavaScript codes directly for browser display (not compiled by Babel) and need to take care of users with old browsers, you should consider to use var
because incompatible let
will likely cause problems in old browsers and stop webpage rendering once error occurs.
4. const
const
is also introduced in ES6. Same as let
, it is also scoped at block level. The only difference is that const
variable is a constant, whose values cannot be changed.
"use strict";
const a = 1;
a = 2;
The above code snippet will throw error TypeError: Assignment to constant variable.
In addition, if you are working with arrays or objects, it’s totally fine with constant declarations but modify it’s attributes or members later. Consider the following code snippet:
"use strict";
const a = [];
const b = {};
a.push(1);
b.key = 2;
console.log("a", a);
console.log("b", b);
// output:
// a [ 1 ]
// b { key: 2 }
No error is occured. That is because the constant values of a
and b
are their addresses in the memory, instead of their members or attributes. If we assign the address of a
to b
as below, errors will then take place.
"use strict";
const a = [];
const b = {};
a = b; // TypeError: Assignment to constant variable.
Therefore, as long as you do not point a
or b
to another locations, no error would occur.
It is recommanded to do so to ensure that you are operating on the correct instance of object / array.
A little summary
You should never ever declare a variable without var
, let
or const
!
Also, var
should be avoided too unless you really have to consider browser compatibility issues.
The good practice is that you should always consider declaring a variable using const
.
Using const
by default helps you avoid unnecessary mistakes such as carelessly re-assign values to an important variable. unless you are sure that you would change its values later. Then the second option should always be let
.