But, what is the difference between var, let, and const? š¤
Some interviews in the UK asked about the difference between var, let, and const in JavaScript. And I decided to share what I think about them and what itself with few words, this way I fixed the conception in my mind as well. :)
Var
In this code JavaScript, var is the older option for declaration news variable for JS. It is a lot used before the specification 2015 (ES6). We can declare a variable globally, or locally. For both cases, it is a consideration of the block scope.
redeclaration or update
We can declare the variable and redeclaration that in the same or another scope.
var test = "hello world zero"
var test = "hello world one"
or just
test = "hello world three"
var hoisting
Initialization of the var is optional, but if the var was not the initial value, for default value is undefined
before the code run, and it call
According to Mabishi Waki in
Hoisting is
a JavaScript mechanism where variables and function declarations are moved to the top of their scope before code execution.
The sample below is possible, without error, because the hoisting mechanism.
console.log (test);
var test = āhello worldā
// undefined
Let
It was to add on specification ECMAScript 2015 ā ES6. introduced two new keywords let and const for declaring variables.
redeclaration or update
The declaration is limited to the scope of a block statement, such as a function. We can not do the declaration twice, if you do that, will happen an error.
let x = 1; let x = 2
// Uncaught SyntaxError: Identifier āxā has already been declared
But we can update the variable as many times as you want.
let x = 1; x = 2; x = 3; x = 4;
The world let came from Mathematics, this word is a lot of in math prepositions, like at the beginning of the Theorem.
var hoisting
It is not applying. if you do that, will happen an error as well.
console.log (test);
let test = āhello worldā
// Uncaught ReferenceError: test is not defined
Const
It cannot be redeclared or updated. It needs to be initialized, if it is not initialized we will have a compile error.
const SHOULD_BE_INITIALIZED = "Hello World";
reinitialized
const TEST; TEST = "Hello World"
// Uncaught SyntaxError: Missing initializer in const declaration
redeclaration
const TEST = "Hello World"; TEST="Hello World 2"
// Uncaught SyntaxError: Identifier ātestā has already been declared
References: