flight & const

flight & const

Common characteristics

Block scope

The keywords let and const in front of the variable declare the variable, which is available only in its local domain, the so-called “block scope”. When a variable is declared with let/const within curly braces, then the curly braces are the edges of its domain.

let & const

No hosting variable at compile time

Variables declared with “let/const” are not hoisted to the top of the block, as variables declared with “var” do.

Do not create global variables

It should be noted that “let/const” keywords do not make global variables even when in the global domain:

Specifics of the “flight” keyword

Block scope

A variable can be declared with the keyword “let” and outside the curly braces, and it will still belong to the domain that makes up the curly braces. This exception applies to the case when a variable is declared within an iteration bound expression:

Redeclaring a variable in the same block causes a Syntax Error

Unlike declaring a variable with the “var” keyword where redeclaration of the variable is allowed, redeclaring a variable in the same domain with the “let” keyword is not allowed, and throws an error.

For this reason, care should be taken not to use it within the “switch” expression because it is all one domain:

This problem can be overcome as follows:

Solves the problem of iteration and setTimeout() methods

Using the keyword “let” instead of “var”, within the “for…loop”, simply solves a known issue related to iteration within the setTimeout method.

Since the “let” keyword redefines a new variable “i” at each iteration of the loop, then the expected result is obtained:

See more about this problem in the article (Impossible Errors in JavaScript).

Specificity of the “const” keyword

Variables declared with the keyword “const” generate a constant. Constants in JavaScript are “immutable variables”, ie. variables that cannot be reassigned new content.

Variability of constant content!?

It should be noted that immutability only applies to the variable, but not to the immutability of the constant content!

or as in the following example adding new members to the array will not throw an error:

A real constant with immutable content

If we would like the content to be immutable, then we need to use the method Object.freeze():

See more about “Object.freeze()” in the article “Object() & Object.prototype”