JavaScript let Keyword

By far we have seen how to declare a variable in JavaScript. We have done this using the ‘var’ keyword. But there is another keyword in JavaScript which is used to declare a variable, and it is the JavaScript ‘let’ keyword.

The let keyword was introduced in 2015 with ES6. It is a way to declare block-scoped variables.

Some basic characteristics of the ‘let’ keyword:

  • If a variable has been declared using the let keyword, it cannot be redeclared within the same scope. However you can redeclare a variable in different block scopes.
  • A variable must be declared before use.
  • A variable defined with the let keyword has block scope.

Example

let name = 'Mango';
let name = 'Banana';

This code will through an error saying that name has already been declared.

However, with ‘var’ keyword you can redeclare a variable.

var name = 'Mango';
var fruit = 'Banana';
//Valid code. Nothing is incorrect

Block Scope

JavaScript only had two types of scope before ES6. They were- Global scope and function scope.

ES6 introduced the keywords let and const that provide block scope in JavaScript. Variables declared inside a {} block cannot be accessed from outside the block.

Example

{
  let fruit = 'Mango';
}
// fruit cannot be used here

However, variables declared with the var keyword does not have block scope. And therefore, a variable declared using var keyword inside a block can be accessed from outside it.

{
  var fruit = 'Mango';
}
// fruit can be used here also

Redeclaration of variables

If you are using the var keyword to redeclare a variable inside a block, it can cause problem.

var num = 12;
// Here num is 12

{
    var num = 4;
    // Here num is 4
}
// Here num is 4

This problem can be solved using the let keyword.

let num = 12;
// Here num is 12

{
    let num = 4;
    // Here num is 4
}

// Here num is 12

Redeclaration of a variable is allowed anywhere in the script by using ‘var’ keyword.

var num = 12;
// Now num is 12

var num = 4;
// Now num is 4

Redeclaring a variable with let keyword in the same block is NOT allowed

var num = 12;   // This is allowed
let num = 4;   // This is not allowed

{
    let num = 7;   // This is allowed
    let num = 11;   // This is not allowed
}

{
    let num = 5;   // This is allowed
    var num = 1;   // This is not allowed
}

However, it is completely ok to redeclare a variable in another with let keyword.

let num = 12;   // This is allowed

{
    let num = 4;   // This is allowed
}

{
    let num = 14;    // This is allowed
}