💻ES6 tutorial: let in javascript

Rafi kadirRafi kadir
2 min read

In ES5, we used to declare a variable using var. ES6 provides a new way of declaring a variable by using the let keyword.

But there are some differences between let and var. Let’s understand some concepts related to let.

Block Scope:

Variables declared with let are block-scoped. In JavaScript, blocks are denoted by curly braces {}. Variables declared inside the { } block cannot be accessed from outside. For example, the if, if...else, do...while and for loop statements create blocks.

let age = 10;
  if (age === 10) {
    let age = 20;
    console.log(age);
    // Expected output: 20
  }
console.log(age);
// Expected output: 10

Explanation: There are two let one is inside if condition (block scope )and another is outside of the block.

The first console.log(age) statement inside the if block will output 20 because it refers to the inner age variable declared within that block.

The second console.log(age) statement outside the if block will output 10 because it refers to the outer age variable declared at the beginning of the code.

Declaring Variables:

Variables declared with let cannot be redeclared within the same block or same scope.

let a = 5;
let a = 3; // error

OUTPUT: Uncaught SyntaxError: Identifier 'a' has already been declared

Redeclaring a variable with let in a different scope or block treats that variable as a different variable. And the value of a variable outside does not change.

let a = 5;
{
    let a = 3;
    console.log(a); //Output: 3
}
console.log(a); //Output: 5

Hoisting:

the let keyword in JavaScript does not allow hoisting. When you declare a variable using let, it is not hoisted to the top of its containing scope.

console.log(a);
let a; // ReferenceError: a is not defined

👉 Follow my IG for regular frontend tips: Rafi Kadir
👉 Make a connection on Linkedin: Rafi Kadir

0
Subscribe to my newsletter

Read articles from Rafi kadir directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Rafi kadir
Rafi kadir

Hello, I am Rafi kadir and I am from Bangladesh. Taking Web Development as a profession not only fulfills my pocket but also my heart because it has been my passion since my early teenage.