KandZ – Tuts

We like to help…!

Javascript 5 🧬 variable hoisting and var vs let

a - variable hoisting
Hoisting is a JavaScript behavior where variables and function declarations are moved to the top of their containing scope
This means you can use variables or functions before they are declared.
This happens when you use var for the declaration
using let and const it gives different result. It results in a Reference Error.
Summary: var → hoisting happens, variable is initialized with undefined
let and const → variables are in a temporal dead zone until declared
function declarations → entire function hoisted to the top of its scope

b - var vs let
var declared variables are function scoped.
let declared variables are block scoped
for var declared variables hoisting happens, variable is initialized with undefined
for let declared variables are in a temporal dead zone until declared
var declared variables can be re-declared within the same scope
let declared variables cannot be re-declared within the same scope
var re-declaration example → No error, re-declaration is allowed
let re-declaration example → SyntaxError: Identifier 'e' has already been declared

Leave a Reply