Super Micro Tutorial

Learn Something In 2 Minutes or Less!

Mar 11th, 2018


JavaScript 'let' vs 'var'

'let' in JavaScript (ES6) allows you to declare variables with block scope rather than function scope (which is what 'var' does):
function foo()
{
    var x = 5;
    let y = 5;

    if (/*something*/)
    {
        var x = 10;     // Oh no! This is the same x from above!
        let y = 10;     // Brand new variable scoped to this block only
    }

    console.log(x);     // 10
    console.log(y);     // 5
}

All 'var' declarations of the same name within a function map to the same variable - kinda silly, right? Especially if you come from a language where block scoping is the norm.

Stick with 'let' and avoid the confusion.