Javascript let declaration

Introduction

We can use let to define variables in Javascript.

let is similar to var.

The difference is: let is block scoped, but var is function scoped.

if (true) { // w  w w. j  a  v  a2  s  .  co  m
   var name = 'CSS'; 
   console.log(name);  // CSS 
} 
console.log(name);    // CSS 
            
if (true) { 
   let age = 12; 
   console.log(age);   // 12 
} 
console.log(age);     // ReferenceError: age is not defined  

Here, the age variable cannot be referenced outside the if block because its scope does not extend outside the block.

Block scope is a subset of function scope, so any scope limitations that apply to var declarations will also apply to let declarations.

A let declaration does not allow any redundant declarations within a block scope.

Doing so will result in an error:

var name; 
var name;  //OK

let age; 
let age;  // SyntaxError; identifier 'age' has already been declared 

The following is perfect legal Javascript code:

var name = 'HTML'; 
console.log(name);  // 'HTML' 
if (true) { //ww w. j  a v a 2  s . co m
   var name = 'CSS'; 
   console.log(name);  // 'CSS' 
} 
            
let age = 30; 
console.log(age);  // 30 
if (true) { 
   let age = 26; 
   console.log(age);  // 26 
}  

The different keywords do not declare different types of variables.

Only the scope is different.

 
var name; 
let name;  // SyntaxError 
              
let age; 
var age;   // SyntaxError 

let does not support hoisting:

// name is hoisted 
console.log(name);  // undefined 
var name = 'CSS'; 
              
// age is not hoisted 
console.log(age);  // ReferenceError: age is not defined 
let age = 26;  



PreviousNext

Related