Difference between var, let, const

Difference between var, let, const

  1. var declarations are globally scoped or function scoped while let and const are block scoped.
  2. var variables can be updated and re-declared within its scope; let variables can be updated but not re-declared; const variables can neither be updated nor re-declared.
  3. They are all hoisted to the top of their scope but while var variables are initialized with undefined , let and const variables are not initialized.
  4. While var and let can be declared without being initialized, const must be initialized during declaration.
1 Like

let, const these are Es6 keywords which can accessed within the block scope.
var->Global scope/function scope.
const

function sample(){
var a=1 //function scope
if(a===1){
const b= “this is block scope”
console.log(b) //prints “this is block scope”
b=“updation cann’t be done” // error->Re-assignment to constant variable is not accepted.
}
console.log(b) //b is not defined
}

let

function sample(){
var a=1 //function scope
if(a===1){
let b= “this is block scope”
console.log(b) //prints “this is block scope”
b=“updation can be done” // re-assignment is accepted
console.log(b)
}
console.log(b) //b is not defined
}

The main difference between let and const the variable declared with let keyword can be updated with new value but for const the re-assignment is not accepted.

1 Like

var variables can be updated and re-declared within its scope.
let variables can be updated but not re-declared.
const variables can neither be updated nor re-declared.
They are all hoisted to the top of their scope but while var variables are initialized with undefined , let and const variables are not initialized.

difference between using “let” and “var”

Variables declared by “var” keyword are scoped to the immediate function body (function scope) while “let” variables are scoped to the immediate enclosing block denoted by {…} (block scope).

Variable declared with var keyword can be re-declared and updated in the same scope while variable declared with let keyword can be updated but not re-declared.

Variables defined with let are hoisted to the top of the block , but not initialized. This means that the block of code is aware of the variable, but it cannot be used until it has been declared. So, using a let variable before it is declared will result in a ReferenceError.