Blocks

If we consider statements as containers of expressions, then we can consider blocks as containers of statements. In other languages, they are sometimes called compound statements as they allow several statements to exist together.

Strictly speaking, blocks are statements. From a language-design perspective, this is a useful thing because it allows statements that form part of other constructs to be expressed as either single-line statements or entire blocks containing several statements—for example, following if(...) or for(...) constructs.

Blocks are formed by delimiting zero or more statements with curly braces:

{
// I am inside a block
let foo = 123;
}

Blocks are very rarely used as completely isolated units of code (there's very limited benefit from doing so). You'll usually find them within if, while, for and switch statements, as follows:

while (somethingIsTrue()) {
// This is a block
doSomething();
}

The {...} part of the while loop here is a block. It is not an inherent part of the while syntax. If we wish to, we can entirely exclude the block and in its place just have a regular single-line statement:

while (somethingIsTrue()) doSomething();

That would be identical to the version in which we use a block, but obviously this would be limiting if we intend to add more iteration logic. As a result, it's usually preferable to preemptively use a block in such scenarios. Doing so has the added benefit of legitimizing indentation and the containment of the iteration logic.

Blocks are not only syntactic containers. They affect the runtime of our code as well by providing their own scope, which means that we can declare variables within via const and let statements. Observe here how we declare a variable within an if block and how it is not available outside that block:

if (true) {
let me = 'here';
me; // => "here"
}

me; // ! ReferenceError

Scoping is a topic that we should not take lightly. It can be quite difficult to understand, and so what follows is an entire section in which we explore its nature and nuances.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.254.44