1

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?

Randomblue
  • 112,777
  • 145
  • 353
  • 547
  • [Scope Cheat Sheet](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Scope_Cheatsheet) – epascarello Jul 10 '13 at 16:21
  • you call functions, not blocks. if you want callable logic, use [].map instead of for, boolean-return functions instead of if, and so on. – dandavis Jul 10 '13 at 16:26
  • It is basically just like defining `a` in a function, it is only visible in inner scopes. – kitsu.eb Jul 10 '13 at 16:27

2 Answers2

1

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
}
000
  • 26,951
  • 10
  • 71
  • 101
0

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.

Aadit M Shah
  • 72,912
  • 30
  • 168
  • 299