Question

JavaScript has many types of block, such as while blocks, if blocks , for blocks. ES6 introduces block scoping, so "purely semantic", "anonymous" blocks make sense:

{ let a = 'I am declared inside a block'; }
console.log(a); // ReferenceError: a is not defined

What is the above type of block (used only for scoping) called?

Was it helpful?

Solution

Here is the associated documentation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/New_in_JavaScript/1.7#Block_scope_with_let_(Merge_into_let_Statement)

The let statement provides local scoping for variables. It works by binding zero or more variables in the lexical scope of a single block of code; otherwise, it is exactly the same as a block statement. Note in particular that the scope of a variable declared inside a let statement using var is still the same as if it had been declared outside the let statement; such variables still have function scoping.

The documentation refers to it as a let block, let expression (if in an expression context), or implicit block in some cases.


In your example:

{ let a = 'I am declared inside a block'; }
console.log(a); // ReferenceError: a is not defined

You cannot get the value of a outside of its scope. That is exactly what the scope is meant to do. However, you can do this:

{ let a; // instantiated inside this block
    a = 'I am assigned inside a block';
    console.log(a); // returns the value of a
}

OTHER TIPS

I would assume that they are called let blocks. According to MDN I seem to be superficially right:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/New_in_JavaScript/1.7#let_statement

Read the "Scoping rules" section under let statement.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top