jskatas.org Continuously Learn JavaScript. Your Way.

Block scope: let declaration

let restricts the scope of the variable to the current block.

let restricts the scope of the variable to the current block

comparing var with let

WHEN using var for declaring a variable THEN the scope of the variable is the surrounding function
//: {"jskatas": {"terms": ["block", "scope"]}} if (true) { let varX = true; } assert.equal(varX, true);
WHEN declaring a variable using let THEN the scope is limited to the surrounding block (enclosed in { and })
if (true) { var letX = true; } assert.throws(() => letX, ReferenceError);

using let

WHEN using let in a for loop THEN the variable is only "visible" inside this loop
let obj = {x: 1}; for (var key in obj) {} assert.throws(() => key, ReferenceError);
WHEN embedding a let variable in a block (using curly braces) THEN the variable is not "visible" outside of it
{ var letX = true; } assert.throws(() => letX, ReferenceError);
WHEN declaring a variable with let without a value THEN this variable has the value undefined
let variable = 42; assert.strictEqual(variable, undefined);

Related Katas

Block scope

Difficulty Level

BEGINNER

First Published

23 March 2015

Stats

5 tests to solve