One of the most widely used elements introduced in ES6 is the let variable initialization. Why is it better then var? Let’s see.

The main similarity is that var and let allow you to initialize a variable without assigning a value. Afterwards, you can update and change that value.

let value;

value = 'string';

value = 1;

console.log(value);

// 1

And that’s where the similarities end.

1. Block scope

function sayWhaaaat() {
    for(var i = 0; i < 4; i++) {
        var value = i;
    }
    console.log(value)
}

sayWhaaaat()

// 3

What’s going on above? We declare using var a variable called value. And we can access it outside the block! If you try you will be able to console.log the i as well.

Initializing all variables using let will prevent similar issues as let is truly block scoped! When you replace the var with let and try to access it you will get Uncaught ReferenceError: value is not defined.

#javascript #es6 #programming

What I Wish Every Developer Knew About let In Javascript
4.10 GEEK