Difference Between var and let in JavaScript

Difference between var and  ES6 let keyword.

Both var and let are used to declare variables in javascript, but the difference is that var is function scoped and let is block scoped.

In this article, we will see the difference between var and let keyword introduced in ES6.


Javascript let variable have their scope in the block, and the block contains inside the parent.

Block is the pair of parenthesis in which variable is declared{alertInfo}

function parent(){
  let i=10;
   function child(){
     console.log(`Child ${i}`); // Print Child 10
  console.log(`Parent ${i}`); //Print Parent 10
console.log(i); // Print i is not define


If you declare the same variable in the block scope, javascript will throw an error.

function redclare(){
    let i=10;
    let i=20;
SyntaxError: Identifier 'i' has already been declared


Let variables not initialized until their value is access. While var is initialized to undefined.

function init(){
    var var_x;
    let let_x;
Cannot access 'let_x' before initialization

As a result, variables declared with let reduce the possibility of runtime errors, as the compiler produces compile-time errors. This improves the readability and maintainability of the code.{alertInfo}

Next Post Previous Post
No Comment
Add Comment
comment url