DEV Community

Cover image for 💻ES6 tutorial: let in javascript
rafikadir
rafikadir

Posted on

💻ES6 tutorial: let in javascript

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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

Top comments (2)

Collapse
 
fyodorio profile image
Fyodor

In ES5, we used to declare…

ES6 provides a new way…

FWIW, ES6 is aka ES2015 which means it’s 8 (!) years and the latest spec is ES2023 so… time flies, man it does…

Collapse
 
rafikadir profile image
rafikadir

Yes. but it's crutial to learn es6 so that we can move forward.