JavaScript Interviews
What is the difference between var, let, and const in declaring variables in JavaScript?
Writing Tips:
- • Provide clear explanations with examples
- • Use proper terminology
- • Structure your answer logically
- • Include code examples when relevant
Answer:
🧠 1. Firstly — Why We Have let and const
In older JavaScript (before ES6), we only had var for declaring variables.
But var had some serious problems — mainly related to scope and hoisting.
So in ES6 (2015), let and const were introduced to fix those issues.
⚙️ 2. var, let, and const – Comparison
📝 Important Note: The temporal dead zone (TDZ) is the period in JavaScript from the beginning of a block scope until a variable declared with let or const is initialized. During the TDZ, the variable exists but is in an uninitialized state, and attempting to access it will result in a ReferenceError.
🔵 var
- Scope: Function-scoped
- Redeclaration: Allowed
- Reassignment: Allowed
- Hoisting: Yes (initialized with undefined)
- Default Value before TDZ: undefined
- Default Value after TDZ: undefined
🟣 let
- Scope: Block-scoped
- Redeclaration: Not allowed
- Reassignment: Allowed
- Hoisting: Yes (but TDZ)
- Default Value before TDZ: uninitialized (TDZ) — accessing before initialization throws ReferenceError
- Default Value after TDZ: undefined
🟢 const
- Scope: Block-scoped
- Redeclaration: Not allowed
- Reassignment: Not allowed — but object properties & array elements stay mutable (✅ Mutable content, ❌ Immutable reference)
- Hoisting: Yes (but TDZ)
- Default Value before TDZ: uninitialized (TDZ) — accessing before initialization throws ReferenceError
- Default Value after TDZ: must be assigned on declaration
📍 3. Scope Differences
👉 var — Function Scope
1function example() { 2 if (true) { 3 var x = 10; 4 } 5 console.log(x); // ✅ works → 10 (function scope) 6} 7example();
x is accessible anywhere inside the function, even outside the if block.
👉 let — Block Scope
1function example() { 2 if (true) { 3 let y = 20; 4 } 5 console.log(y); // ❌ ReferenceError (block scope) 6} 7example();
y exists only inside the block {} where it’s declared.
👉 const — Also Block Scope
1if (true) { 2 const z = 30; 3} 4console.log(z); // ❌ ReferenceError
🚀 4. Reassignment vs Redeclaration
✅ var — can redeclare and reassign
1var a = 1; 2var a = 2; // ✅ redeclared 3a = 3; // ✅ reassigned 4console.log(a); // 3
⚠️ let — can reassign but not redeclare in same scope
1let b = 1; 2// let b = 2; // ❌ SyntaxError (can't redeclare) 3b = 2; // ✅ reassigned
🚫 const — cannot redeclare or reassign
1const c = 5; 2// c = 10; // ❌ TypeError
💡 5. Important Detail — const Objects and Arrays
Even though const variables cannot be reassigned, the contents of objects or arrays declared with const can still change:
1const person = { name: "Mohamed" }; 2person.name = "Ali"; // ✅ allowed 3console.log(person.name); // "Ali" 4 5// ❌ but not allowed: 6person = { name: "Sara" }; // TypeError
✅ Mutable content, ❌ Immutable reference
🧩 6. Hoisting and the Temporal Dead Zone (TDZ)
All 3 are hoisted, but behave differently:
1console.log(a); // undefined 2var a = 10; 3 4console.log(b); // ❌ ReferenceError 5let b = 20; 6 7console.log(c); // ❌ ReferenceError 8const c = 30;
varis hoisted and initialized withundefinedletandconstare hoisted but not initialized → exist in Temporal Dead Zone (TDZ) until the line of declaration.
🧠 TDZ means: you can’t access the variable before its declaration — even though JS knows it exists.
⚠️Exception: If you forget var, let, or const
— If you declare a variable without any keyword inside a function, it becomes global accidentally — which is considered bad practice.
Example:
1function badExample() { 2 x = 10; // ❌ no var/let/const 3} 4badExample(); 5console.log(x); // ✅ 10 (created as global variable)
This is why you should always use let or const (never omit them).
🧱 7. Real-World Use Cases
Situation: A variable whose value will change (e.g., loop counter, user input)
Recommended Declaration: let
Situation: A value that must never change (e.g., API_URL, tax rate)
Recommended Declaration: const
Situation: Old code, or compatibility with legacy JS
Recommended Declaration: var (but avoid in modern JS)
What is hoisting in JavaScript? and how does it work?
Writing Tips:
- • Provide clear explanations with examples
- • Use proper terminology
- • Structure your answer logically
- • Include code examples when relevant
Answer:
Hoisting in JavaScript is a behavior where variable and function declarations are moved (“hoisted”) to the top of their containing scope during the compilation phase, before the code is executed.
This means you can sometimes reference functions or variables before you actually declare them in your code — though the behavior depends on how they are declared.
1️⃣ Variable Hoisting
var: The declaration is hoisted, but not the assignment.
1console.log(a); // undefined 2var a = 5;
Internally, JavaScript treats it like:
1var a; // declaration hoisted 2console.log(a); // undefined 3a = 5; // assignment happens later
letandconst: Are also hoisted, but they are in a Temporal Dead Zone (TDZ) until their declaration is evaluated.
Accessing them before the declaration causes a ReferenceError.
1console.log(b); // ReferenceError 2let b = 10;
2️⃣ Function Hoisting
- Function declarations are fully hoisted, including the body:
1greet(); // "Hello" 2 3function greet() { 4 console.log("Hello"); 5}
-
Function expressions assigned to variables behave like variables:
- If declared with
var, the variable is hoisted but the function isn’t assigned yet. - If
letorconstis used, it’s in TDZ.
- If declared with
1sayHi(); // TypeError: sayHi is not a function 2var sayHi = function() { 3 console.log("Hi"); 4}
✅ Why Hoisting Matters
-
It can cause unexpected
undefinedorReferenceErrorif you don’t understand the difference betweenvar,let,const, and function declarations. -
It affects the scope and lifetime of variables and functions.
What is a closure in JavaScript?
Writing Tips:
- • Provide clear explanations with examples
- • Use proper terminology
- • Structure your answer logically
- • Include code examples when relevant
Answer:
A closure in JavaScript is a combination of a function and the lexical environment in which that function was declared.
In simpler terms, it allows a function to remember and access variables from its outer scope, even after that outer function has finished executing.
🧩 What is a Lexical Environment?
A lexical environment is an internal object created by the JavaScript engine whenever a function or block is executed. It stores variables and functions that belong to that particular scope.
When an inner function is created inside another function, the inner one keeps a reference (not a copy) to the outer lexical environment where it was defined.
This is why the inner function can still access variables from its parent, even after the parent function is done executing.
💡 Example: Basic Closure
1function outer() { 2 let count = 0; 3 4 function inner() { 5 count++; 6 console.log(count); 7 } 8 9 return inner; 10} 11 12const counter = outer(); 13counter(); // 1 14counter(); // 2
➤ Step By Step Explanation:
1- When outer() runs, it creates a lexical environment containing { count: 0 }.
2- The inner() function is defined inside that environment and keeps a reference to it.
3- When outer() finishes, we still have access to that environment via the returned inner function.
4- Each call to counter() updates and logs the same count variable.
🧠 Definition Recap:
A closure = function + remembered lexical environment.
☑️ Closures help you:
- 1- Keep data private.
- 2- Maintain state across function calls.
- 3- Write modular, encapsulated code.
🔑 Key Takeaways:
- ● Every function or block has its own lexical environment.
- ● Inner functions keep references to their parent's lexical environment.
- ● The chain of lexical environments forms a closure.
🧰 Real-world Example:
Closures are commonly used to create private variables in JavaScript.
1function createCounter() { 2 let count = 0; // private variable 3 4 return { 5 increment: function() { count++; console.log(count); }, 6 reset: function() { count = 0; console.log("Reset!"); } 7 }; 8} 9 10const counter = createCounter(); 11counter.increment(); // 1 12counter.increment(); // 2 13counter.reset(); // Reset!
🧩 In short: A closure lets a function remember and access variables from its outer scope, even after that scope has finished executing.
What is the Event Loop and how does it work?
Writing Tips:
- • Provide clear explanations with examples
- • Use proper terminology
- • Structure your answer logically
- • Include code examples when relevant
The Event Loop is a mechanism in JavaScript that handles asynchronous operations by continuously checking the call stack and the task queue, ensuring non-blocking execution.
What is the difference between function declaration and function expression?
Writing Tips:
- • Provide clear explanations with examples
- • Use proper terminology
- • Structure your answer logically
- • Include code examples when relevant
Answer:
A function declaration is a function defined using the function keyword followed by its name. A function declaration can be called even before it appears in its scope because it is hoisted.
Example:
1sayHello(); // ✅ works, because of hoisting 2 3function sayHello() { 4 console.log("Hello from a function declaration!"); 5}
A function expression, on the other hand, is a function assigned as a value to a variable. It can be anonymous or named. Named function expressions are useful for recursion or debugging. Unlike function declarations, function expressions are not hoisted, so they cannot be called before they are defined.
Example:
1sayHello(); // ❌ Error: Cannot access 'sayHello' before initialization 2 3const sayHello = function() { 4 console.log("Hello from a function expression!"); 5};
👉 Key differences:
- Hoisting: Function declarations are hoisted, function expressions are not.
- Readability: Declarations make code more structured when functions are used in multiple places.
- Flexibility: Expressions are more flexible since they can be passed as arguments (e.g., callbacks) or stored in data structures.
What is the Arrow Function? What are its advantages and disadvantages?
Writing Tips:
- • Provide clear explanations with examples
- • Use proper terminology
- • Structure your answer logically
- • Include code examples when relevant
No answer available