With JavaScript, the user can declare variables with three keywords, which are let, var, and const. The terms var let and const are somewhat confusing. We will explain all 3 variables with the help of examples.
The difference between the variables var, let as well as const is described below in different ways.
var | let | const |
---|---|---|
It's a function scope | block scope | block scope |
const func = () => {
var val1 = 5;
if(true) {
var val2 = 10;
console.log(val1); //Output 5
console.log(val2); //Output 10
}
}
func();
console.log(val1); //undefined. Not available outside function
console.log(val2); //undefined. Not available outside function
const func = () => {
let x = 10;
if(x === 10) {
let y = 20;
console.log(x); //Output 10
console.log(y); //Output 20
}
console.log(x); // Output 10
console.log(y); // ’undefined'
}
func();
Hoisting is the term used to define a variable prior to its declaration.
var | let | const |
---|---|---|
Allowed | Not allowed | Not allowed |
var1 = 100; |
let1 = 100; |
const1 = 100; |
var | let | const |
---|---|---|
Allowed | Allowed | Not allowed |
var | let | const |
---|---|---|
Allowed | Not Allowed | Not allowed |