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 the var keyword is defined throughout the program.

Example

Output:

let and var keyword

let keyword

The let statement is used to declare a local variable in TypeScript. It is similar to the var keyword, but it has some restriction in scoping in comparison of the var keyword. The let keyword can enhance our code readability and decreases the chance of programming error. A variable declared with the let keyword is limited to the block-scoped only.

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

Example

Output:

The above code snippet throws an error because the variable "hello" is not defined globally.

let and var keyword

Var vs. Let Keyword

SN var let
1. The var keyword was introduced with JavaScript. The let keyword was added in ES6 (ES 2015) version of JavaScript.
2. It has global scope. It is limited to block scope.
3. It can be declared globally and can be accessed globally. It can be declared globally but cannot be accessed globally.
4. Variable declared with var keyword can be re-declared and updated in the same scope.
Example:
function varGreeter(){
  var a = 10;        
  var a = 20; //a is replaced
  console.log(a);
}
varGreeter();
Variable declared with let keyword 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;
}





Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA