Var vs Let vs Const and the temporal dead zone
Learn the new ways of declaring variables introduced in ES6.
We'll cover the following...
With the introduction of let
and const
in ES6, we can now better define our variables depending on our needs. During our JavaScript
primer we looked at the basic differences between these 3 keywords, now we will go into more detail.
Var
#
Variables declared with the var
keyword are function scoped, which means that if we declare them inside a for
loop (which is a block scope), they will be available even outside of it.
Press + to interact
for (var i = 0; i < 10; i++) {var leak = "I am available outside of the loop";}console.log(leak);// I am available outside of the loop
Let’s take a look at an example with a functional scope variable:
Press + to interact
function myFunc(){var functionScoped = "I am available inside this function";console.log(functionScoped);}myFunc();// I am available inside this functionconsole.log(functionScoped);// ReferenceError: functionScoped is not defined