var vs let vs const | Frontend Interview Questions

1. Scope

//var has global scope , work inside or outside the block
//let and const has block level scope

{
var a = 5;
let b = 6;
const c = 7;
}
console.log(a);
console.log(b);
console.log(c);

2. Declaration

Re-declaration under same scope

Let and const cannot be redeclared under same scope , while var can.

//error
let a;
 let a;

//error
 const a;
 const a;

//works fine
var a;
var a;

Re-Declaration under different scope

all 3 can be redeclared under different scope , but

var override the data , as it as global scope

let and const print data depending on their scope.

var a = 1;
let b = 2;
const c = 3;

{
  var a = 4;
  let b = 5;
  const c = 6;
console.log(c);
}

console.log(a);
console.log(b);
console.log(c);

output -
6
4
2
3

Declaration without initialization

Var and let can be declared without initialization , but const can’t.

 var a;
 let a;

//errror
 const a;

Re-initialization

Var can be reinitialized
let can be re-initialized

const cannot be re-initialized

var a = 5;
a = 6;
console.log(a);

let a = 5;
a = 6;
console.log(a);

const a = 5;
a = 6;
console.log(a);

3. Variable Shadowing

//shadow var variable with let – works fine
//shadow let variable with var – error
//const cannot be shadowed

var a = "hey";
function test() {
  var a = "hello";

  if (true) {
    let a = "hi";
    console.log(a);
  }
  console.log(a);
}

test();
console.log(a);

4. Hoisting in var,let and const

During creation phase , java script engines moves all the functions and variable declaration at the top of the code.

let and const cannot be hoisted , meaning let and const are hoisted in Temporal dead zone

var can be hoisted

console.log(a);
let a = 1;
Uncaught ReferenceError: can't access lexical declaration 'a' before initialization

console.log(a);
let a = 1;
Uncaught ReferenceError: can't access lexical declaration 'a' before initialization

console.log(a);
var a = 1;
output - undefined

//how java script engine read the code
var a;
a = undefined
console.log(a)
Temporal Dead Zone : 
It is an area or block where variable are in the scope, but they are inaccessible until they are declared.

Note

Only declaration get hoisted at the top , not the initialization
function Add(){
    console.log(answer)
    var answer = 2
};
Add()

Interview Question

function abc() {
  console.log(a, b, c);
  const c = 30;
  let b = 20;
  var a = 10;
}
abc();

Comment you output below 

Comment your output below and tag me on Instagram

Help Others

Himanshu Shekhar

Hey. I am a software engineer with 3+ years. Along with my job, I create content regarding coding and software engineering in general. I would request you to follow my blog and my video, which will help you in your software engineering journey. Follow me on Youtube →
View All Articles

Leave a Reply

Your email address will not be published.