Javatpoint Logo
Javatpoint Logo

Difference between let and var keyword

var keyword

The var statement is used to declare a variable in JavaScript. A variable declared with var keyword is defined throughout the program.

Example:

let keyword

The let statement is used to declare a local variable in block scope. The let keyword is similar to the var keyword. The let keyword has some restriction in scoping in comparison of var keyword. The let keyword can greatly enhance our code readability and decreases the chance of programming error.

Note: The key difference between var and let is not in the syntax, but it differs in the semantics.

Example:

var Vs let Keyword

SN var let
1. var keyword was introduced with JavaScript. let keyword was introduced in ES 6 (ES 2015).
2. It has function scope. It has block scope.
3. It can be declared globally and can be globally accessed. It can be declared globally but cannot be globally accessed.
4. Variable can be re-declared and updated.
Example:
function varGreeter(){
  var a = 10;        
  var a = 20; //a is replaced
  console.log(a);
}
varGreeter();
Variable can be updated but not re-declared.
Example:
function varGreeter(){
 let a = 10;        
 let a = 20; //SyntaxError: Identifier 'a' 
             //has already been declared
 console.log(a);
}
varGreeter();
5. It is hoisted.
Example:
{
  console.log(c); // undefined. Due to hoisting
  var c = 2;
}
It is not hoisted.
Example:
{
  console.log(b); 
  // ReferenceError: b is not defined
  let b = 3;
}




Please Share

facebook twitter google plus pinterest

Learn Latest Tutorials


B.Tech / MCA