Lesson 5: Mastering JavaScript Variables with challenges!

manoj ymkmanoj ymk
4 min read

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

KeywordScopeHoistingReassignmentRedeclarationTemporal Dead Zone
varFunctionYesYesYesNo
letBlockYes*YesNoYes
constBlockYes*NoNoYes

🚨 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:

  1. Creation Phase – Variables are hoisted.

  2. 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

  1. Declare a const object. Try changing one of its properties. What happens?

  2. What will this log?

     var x = 10;
     (function() {
       console.log(x);
       var x = 20;
     })();
    
  3. Show how variable shadowing works with nested blocks.

🟑 Intermediate

  1. Recreate a setTimeout loop using var and fix the closure issue without using let.

  2. Simulate a TDZ error and explain why it occurs.

  3. Create a scope chain of 3 levels and log variable resolution.

πŸ”΄ Advanced

  1. Explain why this happens:

     let a = a + 1;
    
  2. Build a polyfill that prevents accidental globals in non-strict mode.

  3. Create a quiz where variable declaration order affects outcome. Test it!

  4. Use eval() to dynamically declare a variable. Track its scope.

🎯 Bonus Brain-Twister

  1. 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 but var 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 scope

  • LCB = Let/Const β†’ Block scope

  • TDZ = β€œ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:

  1. User pastes JavaScript code.

  2. Use AST parser (e.g. Acorn.js) to parse code.

  3. Highlight variable scopes (var in blue, let in green, const in orange).

  4. 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.

0
Subscribe to my newsletter

Read articles from manoj ymk directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

manoj ymk
manoj ymk