Lesson 5: Mastering JavaScript Variables with challenges!

What Are Variables in JavaScript?
Variables are named containers for storing data values. In JavaScript, you declare variables using var
, let
, or const
.
let name = "Alice";
const PI = 3.14;
var count = 0;
Scope & Behavior Summary
Keyword | Scope | Hoisting | Reassignment | Redeclaration | Temporal Dead Zone |
var | Function | Yes | Yes | Yes | No |
let | Block | Yes* | Yes | No | Yes |
const | Block | Yes* | No | No | Yes |
π¨ Hoisted but uninitialized (TDZ applies)
Example: Hoisting Differences
console.log(x); // undefined
var x = 10;
console.log(y); // ReferenceError
let y = 20;
Visual: Variable Lifecycle in Memory
Creation Phase
ββ Memory allocated (hoisted, but undefined or uninitialized)
Execution Phase
ββ Assignment happens
πΉ 2. Fill Any Gaps: Advanced Insights, Edge Cases, and Internal Mechanics
π Hidden Internals & Gotchas
π§ Execution Context Internals
During compilation, JS engines (e.g., V8) perform:
Creation Phase β Variables are hoisted.
Execution Phase β Assignments happen.
var
is hoisted with undefined
, while let
and const
enter the Temporal Dead Zone (TDZ) β they're hoisted but inaccessible until declared.
π£ TDZ Example
{
console.log(a); // ReferenceError
let a = 5;
}
π Implicit Global Creation (Strict vs Non-Strict Mode)
function foo() {
undeclaredVar = 10;
}
foo();
console.log(window.undeclaredVar); // 10 in sloppy mode
β Strict mode (
'use strict'
) prevents this and throws an error.
π Variable Shadowing
let x = 5;
{
let x = 10; // shadows outer x
console.log(x); // 10
}
console.log(x); // 5
β Closures Trap with var
for (var i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 1000); // 3, 3, 3
}
for (let i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 1000); // 0, 1, 2
}
πΉ 3. Challenge Me Deeply
π’ Basic
Declare a
const
object. Try changing one of its properties. What happens?What will this log?
var x = 10; (function() { console.log(x); var x = 20; })();
Show how variable shadowing works with nested blocks.
π‘ Intermediate
Recreate a
setTimeout
loop usingvar
and fix the closure issue without usinglet
.Simulate a TDZ error and explain why it occurs.
Create a scope chain of 3 levels and log variable resolution.
π΄ Advanced
Explain why this happens:
let a = a + 1;
Build a polyfill that prevents accidental globals in non-strict mode.
Create a quiz where variable declaration order affects outcome. Test it!
Use
eval()
to dynamically declare a variable. Track its scope.
π― Bonus Brain-Twister
- Without running it β predict the output:
let x = 1;
(function() {
console.log(x);
let x = 2;
})();
πΉ 4. Interview-Ready Questions
β Conceptual
Whatβs the difference between block and function scope?
Why does
let
throw a ReferenceError butvar
does not?Explain hoisting behavior in your own words.
π§ͺ Debugging Scenario
A dev gets undefined
for a variable declared later with var
. Explain why.
πΌ Real-World Scenario
In a React app, a loop renders buttons that trigger alerts showing index numbers β but all show the same number. Why?
π₯ Red Flags
Overusing
var
in modern code.Using
const
when mutation is needed.Ignoring TDZ or implicit globals.
πΉ 5. Real-World Usage
React: Closures and
let/const
essential in hooks and component logic.Node.js: Global pollution can happen with unscoped
var
.Bundlers (Webpack/Rollup): Variable scoping affects tree-shaking and module encapsulation.
Testing Frameworks (e.g., Jest): Test leakage can happen due to improper variable scoping.
πΉ 6. Remember Like a Pro
π§ Mnemonics
VLF =
Var
β Function scopeLCB =
Let
/Const
β Block scopeTDZ = βTrap Donβt Zapβ β Youβll crash if you access before declaring.
πΊ Mind Map
Variables
βββ var
β βββ Function scope
β βββ Hoisted + initialized
β βββ Can be redeclared
βββ let
β βββ Block scope
β βββ TDZ
β βββ No redeclaration
βββ const
βββ Block scope
βββ TDZ
βββ No reassignment
βββ Mutation allowed (for objects)
πΉ 7. Apply It in a Fun Way
π¨ Mini Project: βScope Inspectorβ
Goal: Build a small interactive web app that lets users paste code and highlights scope blocks.
Steps:
User pastes JavaScript code.
Use AST parser (e.g. Acorn.js) to parse code.
Highlight variable scopes (
var
in blue,let
in green,const
in orange).Show hover tooltip with info: scope level, declared/hoisted status, etc.
π Bonus Extension: Show TDZ errors or shadowing issues.
β Bonus Insights
π₯ Common Mistakes
Believing
const
makes object fully immutable.Thinking
var
is block-scoped.Forgetting TDZ in loops or IIFEs.
π Performance Tip
Modern JS engines optimize let
/const
better than var
due to scope predictability.
Subscribe to my newsletter
Read articles from manoj ymk directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
