Today, I assume most of programmers don't use the "var" variable type anymore. Replacing it by "let" and "const". But why? Just because of "var" is just from old version?
This post is to make everybody clear what is difference between them and why "var" is depreciated.
For those who is new to javascript. There are 3 terminologies we should know when creating a variable.
var name;
let age;
const address;
var name;
name = 'minjae'
let age;
age = 30
var name = 'minjae';
let age = 30;
const married = false;
var
can be declared again with same variable name.
let
and const
can not be declared again with same name.
//example
var name = 'Santa';
var name = 'Pikachu'; // OK
let age = 20;
let age = 30; //SyntaxError: Identifier 'age' has already been declared
const character = 'Mario';
const character = 'Bumble Bee'; //SyntaxError: Identifier 'character' has already been declared
"var
" and "let
" can be unassigned during declaration.
"const
" must be assigned during declaration.
//example
var cat //OK
let squirrel //OK
const spider //SyntaxError: Missing initializer in const declaration
"var
" and "let
" can be reassigned.
"const
" can not be reassigned.
//example
var name = "Elgol"
let country = "Germany"
const age = 5
//Reassign
name = "minjae" //OK
country = "Korea" //OK
age = 30 //TypeError: Assignment to constant variable.
what is so bizzare about javascript is that you can access variables before declaring it.
"var
" can be accessed before declaring variables.
"let
" and "const
" can not be accessed before declaring variables.
//example
console.log(cat)
console.log(dog)
//console.log(bird)
var cat //OK
let dog
//result
undefined
console.log(dog)
^
ReferenceError: Cannot access 'dog' before initialization
The phenomenon above is called Hoisting
. It works as if the variables have been lifted to the top.
Hoisting is JavaScript's default behavior of moving all declarations to the top of the current scope.
Variables declared by var
are subject to the declaration
and initialization
stages at once. That is, the variable is declared in the very first line of code (Actually, space for the variable is secured in the memory) and then initialized to undefined
.
// var hoisting example
console.log(movie); //undefined
var movie = 'Forest Gump';
The let
and const
variables are also hosted, but they are not initialized to undefined
. Therefore it emits error when accessed before them.
// let const hoisting example
console.log(music);
console.log(music2);
let music = 'Wonderwall';
const music2 = 'Summer';
//ERROR!!
//ReferenceError: Cannot access 'music' before initialization
As we saw on previous example how each variable type is working, var
has high chance of causing errors.
It is recommened using let
and const
to prevent hoisting and redeclaring problems that you can run application more reliable and safe.