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
snippet
var greeter = "hey hi";
var times = 5;
if (times > 3) {
   var greeter = "Say Hello rookienerd"; 
}
console.log(greeter) //Output: Say Hello rookienerd
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
snippet
let greeter = "hey hi";
let times = 5;
if (times > 3) {
   let hello = "Say Hello rookienerd"; 
   console.log(hello) // Output: Say Hello rookienerd
}
console.log(hello) // Compile error: greeter is not defined

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;
}
Related Tutorial
Follow Us
https://www.facebook.com/Rookie-Nerd-638990322793530 https://twitter.com/RookieNerdTutor https://plus.google.com/b/117136517396468545840 #
Contents +