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.

Scope

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
   }
   child();
  console.log(`Parent ${i}`); //Print Parent 10
}
parent();
console.log(i); // Print i is not define

Redecoration

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

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

Initialization

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

function init(){
    console.log(var_x);
    console.log(let_x);
    var var_x;
    let let_x;
}
init();
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}

إرسال تعليق

Please do not post any spam link in the comment box😊

أحدث أقدم

Blog ads

CodeGuru