Variable Scope — JS Technical Interview Questions & Answers
Global, function and block scope.
Variable Scope
- Variable Scope (js) is a JS topic. In plain words you use it for let total = 0 in a cart script. Don’t start with a slogan — start with that picture.
- Smallest example: let for change, const for fixed. Type it, run it, and say what you see. If you can do that from memory, you know Variable Scope (js).
- From the example next to this theory: Global, function and block scope.
- Trap: var leak / const reassign. Fix that before you talk about advanced JS.
- Viva: what is Variable Scope (js)? Then show let for change, const for fixed. Then name the trap.
Technical Interview Tip: What is Variable Scope (js)? Show this: let for change, const for fixed. Trap: var leak / const reassign.
Code Examples for Variable Scope
Variable Scope — working example
function demo() {
if (true) {
var a = 1;
let b = 2;
const c = 3;
console.log(b, c);
}
console.log(a); // 1 — var is function-scoped
// console.log(b); // ReferenceError — let is block-scoped
}
demo();
console.log(typeof undeclaredVar); // undefined (never declared with let/const)Variable Scope — var is function-scoped and hoisted; let/const are block-scoped. Prefer const, then let.
How to Explain Variable Scope to an Interviewer
What is Variable Scope (js)?
Used for let total = 0 a cart script Not just the heading
Give one small example of Variable Scope (js).
let for change, const for fixed Global, function and block scope
What mistake do beginners make with Variable Scope (js)?
var leak / const reassign Show the fix
Where do you use Variable Scope (js)?
a cart script let total = 0