Variables & Operators
Variables & Operators: JavaScript's `var`, `let`, and `const` are like three different storage containers: `var` is a leaky bucket — its value can seep outside function boundarie
JavaScript's `var`, `let`, and `const` are like three different storage containers: `var` is a leaky bucket — its value can seep outside function boundaries (hoisting + function scope). `let` is a lidded box — the value is changeable but only accessible within its declared block. `const` is a sealed box — filled once, the reference can never be changed. Why three keywords? `var`'s function scope caused unexpected behavior in loops: a `var i` inside a `for` loop remained accessible outside — this never happens in Java because all Java variables are block-scoped. ES6 introduced `let` and `const` to fix this. Comparing Java's `final` with `const`: both forbid reassignment, but if `const` holds a reference to an object, the object's contents can still change — just like Java's `final List list` allows you to add elements. QA perspective: a locator variable declared with `const` stays fixed throughout the test, protecting against accidental reassignment.
Differences between var, let, and const
🎬 The Leak of var: How a Variable Escapes Its Block
ReferenceError (TDZ)
`if (true) { var score = 95; }` — score is declared INSIDE the if block. In Java, the variable would die when the block ends. In JavaScript, `var` behaves DIFFERENTLY.
`console.log(score)` is called outside the block — and it PRINTS `95`! `var`'s function-scope nature leaks the value past the block boundary.
Contrast — write the SAME code with `let score = 95;` and `let` is SEALED to the block. Outside the block, `console.log(score)` no longer leaks — it throws an ERROR instead.
Accessing `let`/`const` before declaration triggers the Temporal Dead Zone (TDZ), throwing a `ReferenceError` — the runtime equivalent of Java's compile-time error.
Final — this is why modern JavaScript defaults to `const`, uses `let` only when reassignment is needed, and almost never uses `var`. This is how scope leaks are prevented.
This code reads a `var` variable BEFORE its value is assigned. What happens?
ReferenceError: testCount is not defined
`var` declarations are HOISTED to the top of the scope — the declaration is already known, only the value has not been assigned yet.
42, then 42 (hoisting carries the value too)
Hoisting only lifts the DECLARATION, not the VALUE — until the assignment line runs, the value is `undefined`.