let) and one way to define a constant value (
const behave the same in terms of scope, both being block scoped (see below). On the other hand,
var behaves differently by being function scoped (see below), meaning
var declarations inside a block scope will also be available to the nearest outer function block.
It is generally preferred to use
const to avoid confusion when it comes to scoping. However, it is important to note that
When we talk about scope, we mean the visibility of one or more entities (e.g variables) to certain parts of our code. There are two types of scopes: global and local. Local scope can in turn be separated into block, function and other types of more specific scopes.
Global scope: Variables defined globally (i.e. not inside a block or function) are part of the global scope and can be accessed from anywhere in the code. When declared in the global scope,
const behave the same in terms of scope.
Local scope: Variables defined inside a block or function can only be accessed from the block or function where they were defined, as well as nested local scopes. When declared inside a block scope,
var will be available but
undefined in outer scopes, while
const will not exist in outer scopes. When declared inside a function scope,
const will all be non-existent in outer scopes.
Written by Angelos Chalaris
If you want to keep in touch, follow me on GitHub or Twitter.