Scoping - Hoisting in Javascript
Scoping - Hoisting in Javascript
Variables declared inside that function scope are only accessible inside
that function, NOT outside.
Also called: Local scope
Block scope (ES6): Everything that is between {} (such as the block of an if
statement, or a for loop..).
Variables declared inside the block are only accessible inside that block
and not outside of it.
Only applied to variables declared with LET or CONST This is why we
say that let and const variables are block scoped.
If we declare a variable using “var” that variable will be accessible
outside the block and would be scoped to the current function or to the
global scope so we say that var is function scoped.
Functions are also block scoped (only in strict mode).
SUMMARY
Scoping asks the question: Where do variables live? or Where can we access a
certain variable, and where not?
3 types of scopes in JS: Global scope, Scopes defined by functions, and scopes
defined by blocks starting in ES6;
Only let and const variables are block-scoped. Variables declared with var end up
in the closest function scope;
In JS we have lexical scoping, so the rules of where we can access variables are
based on exactly where in the code functions and blocks are written;
Every scope always has access to all the variables from all its outer scopes. This is
the scope chain!
When a variable is not in the current scope, the engine looks up in the scope chain
until it finds the variable it`s looking for. This is called variable lookup;
The scope chain is a one-way street: a scope will never, ever have access to the
variables of an inner scope;
The scope chain in a certain scope is equal to adding together all the variable
environments of the all-parent scopes;
The scope chain has nothing to do with the order in which functions were called. It
does not affect the scope chain at all!
Variable environment:
Hoisting: Makes some types of variables accessible/usable in the code
before they are actually declared: “Variables lifted to the top of their
scope”.
In fact: Before execution, code is scanned for variable declarations,
and for each variable, a new property is created in the variable
environment object.
Each let and const variables get their own TDZ that starts at the beginning of the scope
until the line where it is defined and the variable is safe to use after the TDZ.
WHY TDZ?
With this behaviour is easier to catch errors.
Accessing variables before declaration is bad practice and should be avoided and we
should get an error when we try to do so this is what TDZ does.
To make const variable work the way they are supposed to. We can’t reassign const
variables. It would not be possible to set them to undefined first and then assign their
real value later. CONST SHOULD NEVER BE REASSIGNED and it`s only assigned when
execution reaches the declaration.
WHY HOISTING?
Using functions before actual declaration;
Var hoisting is just a byproduct.