Difference between var, let and const in React
In javascript, var
is used to create variables. Because there are challenges with variables specified
using var
, ES6 (ECMAScript 6) added two new
keywords called let
and const
.
Let and const keywords are introduced in ECMAScript 6 (ES6) and are scoped differently from var-based variables.
Scoping guidelines
When var
is declared within a function, it is function scoped means scoped to the immediate function
body, while variables defined with the let
keyword are scoped to the immediate enclosing block {} so it
is block scope.
Example
var userName = "Joe";
function AddEmployee() {
var userName = "Mike";
var role = "Admin";
}
//It will throw 'ReferenceError: role is not defined'.
console.log(role);
//output: Joe
console.log(userName);
Example
for (let i = 0; i < 5; i++) {
console.log(i);
}
// console.log(i); //ReferenceError
for (var j = 0; j < 5; j++) {
console.log(j);
}
console.log(j); // j is accessible
What is var hoisting?
Hoisting allows us to retrieve values from variables and functions even before they are initialization or assign without causing problems.
Is hoisting allowed with VAR?
In regards to variables and constants, the keyword var
is hoisted, whereas let
and
const
are not.
Example: var
hoisting
function addEmployee() {
// output: undefined
console.log(userName);
var userName = "Joe";
// output: Joe
console.log(userName);
}
Example: let
hoisting
function addEmployee() {
// output: ReferenceError
console.log(userName);
let userName = "Joe";
// output: Joe
console.log(userName);
}
Redeclaration
Var allows you to re-declare the same variable in the same scope in strict mode, whereas
let
throws a SyntaxError
.
var userName = "Joe";
var userName = "Mike"; // run successfully and replaces the value.
let role = "Admin";
let role = "Supervisor"; // SyntaxError for role already declared
Const
Const variable is a block scope, cannot be redeclared or cannot be changed once declared.