JS Variable scope: var vs. let vs. const

By YuwebDesign

Variable scope: var vs. let vs. const

Variable scope

Global Variable
When you declare a variable outside of any function,
it is called a global variable,
because it is available to any other code
in the current document.

Local Variable
When you declare a variable within a function,
it is called a local variable,
because it is available only within that function.

Block Statement Scope
In JavaScript before ECMAScript 2015
there is no block statement scope.


That is why var declared within a block

  1. function scope
    is local to the function that the block resides within
    (or the function context if the code is part of a function),
  2. global scope
    within a block (e.g. if statement block)
    the scope of var is the global context
    (the scope of var is not limited to the immediate if statement block.

Hoisting with var
Variables declared vith var are hoisted.

let, const

ECMAScript 6 (ES6/ES2015)
introduced the let and const keywords
that support the declaration
of block scope local variables.

This means the variable
will be confined to the scope
of a block that it is defined in
(e.g., if statement or for loop)
and will not be accessible
outside of the opening and closing curly braces
of the block.

This is contrary to var declarations
which are accessible outside blocks
they are defined in.

Hoisting with const/let
Variables declared vith let/const are hoisted but not initialized.

Trying to access let/const variables before they were declared
will result in ReferenceError

let vs. const

The difference between let and const
is that a const declaration is,
as the name implies,
constant – a read-only reference to a value.

This does not mean the value is immutable,
just that the variable identifier cannot be reassigned.

Leave a Reply or Comment

Your email address will not be published. Required fields are marked *