java script interview
why u use node with express js
how react js is diffreant
why u choose mern stack
what difficulties in that
When to Use RDBMS vs NoSQL in Applications
1. Use RDBMS (Relational Database) when:
Feature Why RDBMS is Suitable Example
Structured, predictable Fixed schema with tables, Banking system where account
data rows, columns details have strict formats
Supports joins, foreign keys, E-commerce where products,
Complex relationships
constraints customers, and orders are linked
Strong consistency Transactions ensure data Flight booking system where seat
required (ACID) integrity allocation must be exact
SQL provides powerful HR payroll system with monthly
Complex queries
querying and aggregation reporting
2. Use NoSQL (MongoDB, etc.) when:
Feature Why NoSQL is Suitable Example
Flexible / evolving Schema-less JSON-like Social media posts where fields
schema documents vary by post type
Large volumes of Handles images, logs, IoT Logging system storing events
unstructured data data easily with different structures
Horizontal sharding and Online multiplayer game storing
High scalability
replication millions of player sessions
High write/read Optimized for speed over
Real-time chat application
throughput complex transactions
java script interview 1
JavaScript is a synchronous single-threaded language.
3. Why is it important?
Because JavaScript is single-threaded + synchronous by default, one slow
task can block everything (UI freeze, delayed clicks, etc).
That’s why JavaScript uses asynchronous techniques (like setTimeout ,
Promises, async/await) with the event loop to avoid blocking.
2
When script is run an execution context is created. It contains two blocks:
One memory block and second code block.
Memory block contains all the variables and functions as key value pairs and code
blocks is where all the code is executed line by line.
Memory block is also called environment variable and the code block is known as
thread of execution.
1. Whenever any JavaScript code is executed an execution context is created
and it is the Global Execution Context.
2. An Execution Context is basically a box which has two components called
Memory Component(Variable Environment) and Code Component(Thread Of
Execution).
3. The Execution context is created in two phases
a. Memory Creation Phase : In this Phase, Memory is allocated to all the
variables and functions which are present in the global scope. Special
keyword Undefined in case of variables and literally the whole function in case
of functions.
java script interview 2
b. Code Execution Phase : In this Phase, code is executed line by line.
4 . Phases of EC Creation:
Memory Creation Phase: Allocates memory for variables and functions.
Code Execution Phase: Executes code line by line, assigns values, and
runs functions.
Function Calls:
Each function invocation creates a new Execution Context.
Parameters are allocated memory in the function’s EC.
When a function returns, its EC is popped off the Call Stack.
Call Stack:
A stack that keeps track of the order of Execution Contexts.
GEC is pushed first. Function ECs are pushed/popped as they run.
When the stack is empty, the program ends.
3
1. Hoisting in JavaScript is a process in which all the Variables, Functions and
Class defination are declared BEFORE execution of the code
2. Variables are initialised to UNDEFINED when they are declared and Function
defination is stored AS IT IS.
3. They are declared in Memory Allocation Phase in the Memory Component of
Execution Context, so we can use them even BEFORE they are declared.
4. UNDEFINED means Variable has been declared but value is not ASSIGNED but
NOT DEFINED means Variables is NOT DECLARED.
5. When we assign Variable to a Function defination, we CAN NOT call this
Variable as Function BEFORE declaration as it will behave as Variable with
UNDEFINED value.
java script interview 3
4
Scope of a variable is directly dependent on the lexical environment.
2. Whenever an function is called an execution context is created, along with this
a lexical environment is created. Lexical environment is the local memory along
with the lexical environment of its parent. Lexical as a term means in hierarchy or
in sequence.
3. Having the reference of parent's lexical environment means, the child or the
local function can access all the variables and functions defined in the memory
space of its lexical parent.
4. The JS engine first searches for a variable in the current local memory space, if
its not found here it searches for the variable in the lexical environment of its
parent, and if its still not found, then it searches that variable in the subsequent
lexical environments, and the sequence goes on until the variable is found in some
lexical environment or the lexical environment becomes NULL.
5. The mechanism of searching variables in the subsequent lexical environments
is known as Scope Chain. If a variable is not found anywhere, then we say that the
variable is not present in the scope chain.
🔹 1. Be accessed before initialization
Variables declared with let and const cannot be accessed before their
declaration.
If you try, you get a ReferenceError.
This period (from entering the scope until initialization line) is called the
Temporal Dead Zone (TDZ).
🔹 2. Temporal Dead Zone (TDZ)
java script interview 4
TDZ exists from the start of scope → until variable is declared.
You can’t access the variable during TDZ.
[Link](a); // ❌ ReferenceError
let a = 10;
🔹 3. [Link] or [Link]
var variables in global scope are attached to the window (in browsers) or global .
let and const are not added to window .
var x = 10;
let y = 20;
[Link](window.x); // ✅ 10
[Link](window.y); // ❌ undefined
🔹 4. Redeclaration
You cannot redeclare a variable with let or const .
With var , you can redeclare in the same scope.
var a = 1;
var a = 2; // ✅ Allowed
let b = 1;
let b = 2; // ❌ Error
🔹 5. const declaration
java script interview 5
const must be declared and initialized on the same line.
const a; // ❌
Error
const b = 10; // ✅
🔹 6. Types of Errors
1. ReferenceError → accessing undeclared/TDZ variable.
2. TypeError → doing invalid operation on type (e.g., calling a number like
function).
3. SyntaxError → invalid code structure.
[Link](x); // ReferenceError
123(); // TypeError
let let = 5; // SyntaxError
🔹 7. Best practice: use const , then let
const prevents accidental reassignments.
Use let if value must change.
Avoid var (because of hoisting + function scope issues).
🔹 8. Initialize variables at top
Declaring at top reduces TDZ.
Helps avoid ReferenceErrors.
🔹 9. Code inside {} = Block
java script interview 6
{
let a = 10;
}
🔹 10. Why Block exists?
To group multiple statements where JS expects only one (like in if , for ,
functions).
🔹 11. Block scope
let & const live inside block memory.
They don’t leak out into global.
var ignores block scope → goes to function/global scope.
🔹 12. Shadowing
If you declare a variable with the same name inside an inner scope, it
shadows (hides) the outer one.
let a = 10;
{
let a = 20; // shadows outer a
[Link](a); // 20
}
[Link](a); // 10
🔹 13. Shadow rules
Shadowing is fine, but it must not cross scope boundaries incorrectly.
🔹
java script interview 7
🔹 14. Illegal Shadowing
You cannot shadow a let with a var .
let a = 10;
{
var a = 20; // ❌ Illegal shadowing
}
🔹 15. var scope
var variables are function-scoped or global-scoped.
They can be accessed outside {} blocks.
{
var x = 100;
}
[Link](x); // ✅ 100
🔹 16. Shadowing definition
Shadowing = redeclaring a variable with the same name in an inner scope.
What is JSON?
🔹 JSON stands for JavaScript Object Notation.
It’s a lightweight data format used to store and exchange information between a
server and a client (like browser ↔️ backend).
🔹 17. Closures
A closure is created when:
java script interview 8
1. A function is defined inside another function,
2. The inner function remembers variables from the outer function,
3. Even after the outer function has finished running.
👉 In short: Closure = Function + its lexical (outer) scope
Why Closures are Useful
Used in higher-order functions like map , filter , reduce .
Closures are important because they let functions remember values and protect
data, making your code more powerful, reusable, and secure.
🔹 18. Function remembers environment
Even if function is returned, it remembers variables from where it was
created.
function outer() {
let a = 10;
return function inner() {
[Link](a); // remembers "a"
};
}
const fn = outer();
fn(); //✅ 10
🔹 19. Returning functions
You can directly return a function like this:
return function x() { ... }
java script interview 9
This returns the function itself (not its result).
📌(Summary
JavaScript Data Types & Tricky Cases
Table)
Case / Expression Output Type / Explanation
Historical JS bug (null is a
typeof null "object"
primitive, not object)
typeof NaN "number" NaN is still considered number
undefined = declared but not Loose equality ( null ==
undefined vs null assigned null = assigned empty undefined ) → true, strict
value equality → false
isNaN("hello") true Converts string → NaN
[Link]("hello") false Strict check, no conversion
typeof [] "object" Arrays are objects internally
[Link]([]) true Correct way to check array
typeof function() {} "function" Special type of object
Falsy values false, 0, -0, "", null, undefined, NaN Everything else is truthy
" " (space) in if
truthy Non-empty string is truthy
condition
"" (empty string) in if falsy Empty string = false
1 + "2" "12" Number converted → string
1 - "2" -1 String converted → number
String auto-converted to
"5" * 2 10
number
"5" + 2 "52" Number converted to string
0 == false true Type coercion in ==
0 === false false Strict equality checks type
java script interview 10
Case / Expression Output Type / Explanation
Both treated as “empty” in
null == undefined true
loose equality
null === undefined false Different types
Object keys ( obj[1] , Keys always converted to
"1"
obj["1"] ) string
Arrays/objects are copied by Changes in one reflect in
Reference types
reference another
parseInt("12px") 12 Stops parsing at non-numeric
parseInt("px12") NaN Starts with non-numeric
parseInt("08") 8 Parsed as decimal
{} + {} "[object Object][object Object]" Objects converted to string
[] + [] "" Both arrays → empty string
[] + {} "[object Object]" Array → "", Object → string
{ } + [] 0 (sometimes) Depends on JS engine
[] == [] false Different references
{ } == { } false Different references
typeof 123 → "number" , then
typeof typeof 123 "string"
typeof "number" → "string"
🔹 20. Returned function is reference
Returned function is a reference, not a copy.
If it changes a variable, the change persists.
🔹 21. setTimeout
setTimeout takes the function out of call stack, keeps a timer.
After timer ends → function put back on call stack → executed.
🔹 22. Without closure + var
java script interview 11
If using var in a loop with setTimeout , all callbacks share the same variable
reference.
So you see the last value.
for (var i=1; i<=3; i++) {
setTimeout(()=>[Link](i),1000);
}
// 4, 4, 4
🔹 23. With let or closure
let has block scope, so every iteration creates a new copy.
Each function gets its own copy of i .
for (let i=1; i<=3; i++) {
setTimeout(()=>[Link](i),1000);
}
// 1, 2, 3
✅ In short:
var → function/global scoped, hoisted.
let/const → block scoped, TDZ, safer.
Shadowing is allowed, illegal if let shadowed by var .
Closure → function + lexical scope.
setTimeout needs closure or let to preserve values.
1. What is Function Statement?
👉 A normal function we create with a name.
java script interview 12
It can be called before it is written, because of hoisting.
// Function Statement
function sayHello() {
[Link]("Hello from Function Statement");
}
sayHello(); // ✅ works
✅ Because JS hoists function statements to the top.
2. What is Function Expression?
👉 When we store a function inside a variable.
It behaves like a variable.
Can’t be called before defining it.
// Function Expression
var greet = function () {
[Link]("Hello from Function Expression");
};
greet(); // ✅ works here
// greet(); before this line ❌ Error (undefined)
3. What is Anonymous Function?
👉 Function without a name.
Usually written where a function is used as a value.
setTimeout(function () {
[Link]("Anonymous Function");
java script interview 13
}, 1000);
Here, function has no name, but still works.
4. What is Named Function Expression?
👉 Function stored in a variable but still has its own name.
var greet = function sayHi() {
[Link]("Named Function Expression");
};
greet(); // ✅ works
// sayHi(); ❌ not accessible outside
5. Parameters vs Arguments
Parameters → Variables written inside function definition.
Arguments → Actual values given when calling function.
function add(a, b) { // a, b → Parameters
[Link](a + b);
}
add(5, 10); // 5, 10 → Arguments
6. First-Class Functions (a.k.a First-Class Citizens)
👉 Functions in JS are treated like values.
This means:
Can be stored in variables.
Can be passed as arguments.
java script interview 14
Can be returned from functions.
function sayHello() {
return "Hello";
}
// Store in variable
let f1 = sayHello;
// Pass as argument
function execute(fn) {
[Link](fn());
}
execute(sayHello); // ✅
// Return a function
function outer() {
return function inner() {
[Link]("Returned Function");
};
}
✅
outer()(); // works
7. Callback Function
👉 A function passed into another function as an argument.
function greet(name, callback) {
[Link]("Hi " + name);
callback();
}
greet("Sagar", function () {
[Link]("Callback Executed");
java script interview 15
});
1. setTimeout helps turn JS which is single threaded and synchronous into
asynchronous.
8. setTimeout makes JS Asynchronous
👉 JS is single-threaded (one task at a time).
But setTimeout helps delay tasks without blocking main code.
[Link]("Start");
setTimeout(() => {
[Link]("Inside setTimeout");
}, 2000);
[Link]("End");
// Output:
// Start
// End
// Inside setTimeout
spread and rest operator
spread operator is used to spread /expand the array /object into the individual
elemant
java script interview 16
rest operator is used in function parameter to collect all the remaining argument
into an array
it is used in fuction parameter and destructing
while the spread is used in array ,fuction call ,object
10. Event Loop, Callback Queue & Microtask Queue
Web APIs (browser powers) handle setTimeout , DOM, fetch etc.
Completed tasks go to queues.
Event Loop checks if Call Stack is empty, then executes them.
Microtasks (Promises, MutationObserver) run before callback tasks.
notes dekh lena ek baar
1. Call Stack
JavaScript runs code line by line.
Each function call is added to the call stack.
When a function finishes, it’s removed from the stack.
java script interview 17
2. Web APIs (Browser features)
Some things are not done by JS itself but by the browser (or [Link] runtime):
setTimeout
DOM events (click, keypress)
HTTP requests ( fetch , XMLHttpRequest )
These run outside JS and notify back when done.
3. Callback Queue (Task Queue / Macrotask Queue)
When async tasks (like setTimeout ) finish, their callbacks go to the callback
queue.
Example:
[Link]("Start");
setTimeout(() => {
[Link]("Timeout callback");
}, 0);
[Link]("End");
👉 Order:
1. "Start" → printed immediately.
2. "End" → printed immediately.
3. Then Event Loop picks the setTimeout callback from the callback queue and
runs it.
Output
java script interview 18
Start
End
Timeout callback
4. Microtask Queue
Special queue for Promises ( .then , .catch , .finally ) and MutationObserver.
Microtasks run before macrotasks (callback queue).
Example:
[Link]("Start");
setTimeout(() => {
[Link]("Timeout");
}, 0);
[Link]().then(() => {
[Link]("Promise");
});
[Link]("End");
👉 Order:
1. "Start"
2. "End"
3. "Promise" (microtask runs before timeout)
4. "Timeout"
Output
java script interview 19
Start
End
Promise
Timeout
5. Event Loop
The event loop is the “traffic controller”.
It checks:
1. Is the call stack empty?
2. If yes → take tasks from microtask queue (promises).
3. If microtask queue is empty → take tasks from callback queue ( setTimeout ,
DOM events).
Repeats forever → keeps app responsive.
🔑 Easy Analogy
Think of a restaurant:
Call stack = Chef cooking right now.
Web APIs = Waiters handling special tasks (oven timer, delivery order).
Microtask queue = VIP orders (Promises) → served first when chef is free.
Callback queue = Normal customer orders (setTimeout, events).
Event loop = Manager who keeps checking → “Chef free? Serve VIPs first,
then normal customers.”
✅ Quick Summary
Call Stack: Executes functions line by line.
java script interview 20
Web APIs: Browser handles async tasks.
Callback Queue (Macrotask): Holds things like setTimeout , DOM events.
Microtask Queue: Holds promises, runs before callback queue.
Event Loop: Keeps checking → when stack is empty, runs microtasks first,
then callbacks.
[Link]("Start");
setTimeout(() => [Link]("Callback Queue"), 0);
[Link]().then(() => [Link]("Microtask Queue"));
[Link]("End");
// Output:
// Start
// End
// Microtask Queue
// Callback Queue
11. JS Runtime Environment
👉 To run JS, we need:
JS Engine (V8, SpiderMonkey etc.)
Web APIs (provided by browser)
Callback Queue
Microtask Queue
Event Loop
12. Parsing → Compilation → Execution
java script interview 21
Parsing: Break code into tokens → AST (Abstract Syntax Tree).
Compilation: Modern JS uses JIT (Just-in-Time compilation).
Execution: Runs code, manages memory, garbage collects.
1️⃣ Parsing
Think of this as reading & understanding the code.
The JavaScript engine takes your raw code (text) and breaks it into tokens
(small pieces like let , = , 10 , ; ).
Then it builds a structure called AST (Abstract Syntax Tree) which represents
the meaning of your code.
👉 Example:
let x = 10;
The engine breaks it into:
Keyword: let
Variable: x
Value: 10
Semicolon: ;
2️⃣ Compilation
Now, the AST is converted into machine-understandable instructions.
In modern JS engines (like V8 in Chrome), this happens using JIT (Just-In-
Time) compilation → it compiles while running and optimizes the code.
Purpose: Make the code fast.
3️⃣ Execution
java script interview 22
Finally, the compiled code is run line by line inside the JS engine.
Variables are stored in memory, functions are executed, results are shown.
The Call Stack + Memory Heap work together to execute everything.
13. DRY Principle
👉 Don’t Repeat Yourself → Use functions to avoid repeating code.
// Bad
[Link]("Hello Sagar");
[Link]("Hello Rohit");
// Good
function sayHello(name) {
[Link]("Hello " + name);
}
sayHello("Sagar");
sayHello("Rohit");
14. Higher-Order Functions
👉 Functions that take other functions as argument OR return them.
function hof(fn) {
return function () {
fn();
[Link]("Higher Order Function");
};
}
function greet() {
[Link]("Hello");
}
java script interview 23
let newFn = hof(greet);
newFn();
15. Array Methods
map → Transform each element.
filter → Select elements.
reduce → Convert array into single value.
let nums = [1, 2, 3, 4];
// map → double
[Link]([Link](n => n * 2)); // [2,4,6,8]
// filter → even
[Link]([Link](n => n % 2 === 0)); // [2,4]
// reduce → sum
[Link]([Link]((acc, n) => acc + n, 0)); // 10
16. Reduce Example (Homework)
const users = [
{ firstName: "Sagar", age: 25 },
{ firstName: "Rohit", age: 35 },
{ firstName: "Amit", age: 20 },
];
const output = [Link](function (acc, curr) {
if ([Link] < 30) {
[Link]([Link]);
java script interview 24
}
return acc;
}, []);
[Link](output); // ["Sagar", "Amit"]
👉 Explanation:
Start with empty array [] .
Check each user.
If age < 30 → add firstName.
Finally return names of young users.
3. Where are Callback functions and Event Handlers stored?
👉 They are stored in Web API environment (provided by browser). Once ready,
they go into the Callback Queue and wait for execution.
4. Where are Promises and Mutation Observers stored?
👉 They are also stored in Web API environment, but when finished, they go into
the Microtask Queue, not the callback queue.
Microtask Queue has higher priority.
5. What does the Event Loop do?
👉 The Event Loop keeps checking if the Call Stack is empty.
If yes → it moves tasks from Callback Queue / Microtask Queue into the Call Stack
for execution.
6. Which queue is given priority: Microtask or Callback?
👉 Microtask Queue (Promises, MutationObserver) runs before Callback Queue
(setTimeout, setInterval, events).
java script interview 25
✅ Example:
[Link]("Start");
setTimeout(() => [Link]("Callback Queue"), 0);
[Link]().then(() => [Link]("Microtask Queue"));
[Link]("End");
// Output:
// Start
// End
// Microtask Queue
// Callback Queue
7. What is Starvation in JavaScript Event Loop?
👉 If too many microtasks are added, callback tasks (like setTimeout) don’t get a
chance to run. This is called starvation.
8. What is the JavaScript Runtime Environment?
👉 It is everything required to run JS code:
JS Engine (e.g. V8)
Web APIs
Callback Queue
Microtask Queue
Event Loop
9. What is inside the JS Runtime Environment?
👉 It contains:
java script interview 26
1. JS Engine (parse + compile + execute)
2. Web APIs (setTimeout, DOM, fetch, etc.)
3. Callback Queue
4. Microtask Queue
5. Event Loop
10. What is a JS Engine?
👉 A program that executes JS code (e.g. Google’s V8).
11. What are the steps of JS Execution?
👉 Parsing → Compilation → Execution
1. Parsing → Code → Tokens → AST (Abstract Syntax Tree)
2. Compilation → JIT (Just-in-Time)
3. Execution → Runs + Optimizes + Garbage Collects
12. What happens in Parsing?
👉 Code is broken into tokens and converted into an Abstract Syntax Tree (AST).
This tree structure is used for execution.
13. What is JIT Compilation?
👉 Modern JS engines use Just-In-Time Compilation → Code is compiled and
executed together, with optimizations.
14. Are Compilation and Execution separate?
👉 No. In modern JS, Compilation + Execution happen together for speed.
15. What optimizations happen during Execution?
👉
Garbage Collection (removes unused memory)
java script interview 27
Inlining (replace function calls with code)
Copy elision (avoid unnecessary copies)
Inline caching (optimize object property access)
16. What happens with setTimeout(…, 0)?
👉 Even if set to 0ms , the callback is put into the Callback Queue and only runs
when Call Stack is empty.
17. Why does setTimeout not run exactly at the given time?
👉 Because if the Call Stack is busy, setTimeout waits longer. The given time is
minimum delay, not exact.
18. What is DRY Principle?
👉 Don’t Repeat Yourself → Avoid repeating same code, use functions.
19. How can Functions help DRY principle?
👉 By wrapping repeating code inside reusable functions.
function greet(name) {
[Link]("Hello " + name);
}
greet("Sagar");
greet("Rohit");
20. What are Higher Order Functions?
👉 Functions that take other functions as arguments or return functions.
function hof(fn) {
return function() {
fn();
java script interview 28
};
}
21. Why are Functions called First-Class Citizens in JS?
👉 Because they can:
Be stored in variables
Be passed as arguments
Be returned from functions
22. What happens if we use [Link]?
👉 That method becomes available to all arrays.
[Link] = function() {
[Link]("Hi from Array");
};
[1,2,3].sayHi(); // Works
23. What is the use of map()?
👉 Transform each element of array.
let nums = [1,2,3];
let doubled = [Link](n => n * 2);
[Link](doubled); // [2,4,6]
24. What is the use of filter()?
👉 Select elements based on condition.
java script interview 29
let nums = [1,2,3,4];
let even = [Link](n => n % 2 === 0);
[Link](even); // [2,4]
25. What is the use of reduce()?
👉 Convert array → single value (sum, min, max, avg).
let nums = [1,2,3,4];
let sum = [Link]((acc, n) => acc + n, 0);
[Link](sum); // 10
26. What arguments does reduce() take?
👉 Two arguments:
1. A function (with accumulator and currentValue )
2. Initial value of accumulator
27. Reduce Example (Homework)
👉 Extract names of users below 30 years.
const users = [
{ firstName: "Sagar", age: 25 },
{ firstName: "Rohit", age: 35 },
{ firstName: "Amit", age: 20 }
];
const output = [Link](function(acc, curr) {
if ([Link] < 30) {
[Link]([Link]);
}
java script interview 30
return acc;
}, []);
[Link](output); // ["Sagar", "Amit"]
🔹 1. How can Event Listeners invoke closures?
👉 First, let’s quickly recall closure:
A closure is when an inner function “remembers” variables from its outer function,
even after the outer function has finished executing.
Now with Event Listeners:
When you attach an event listener (like [Link]("click", ...) ) → you pass
a callback function.
That callback function can access variables from its outer scope (closure).
Even if the outer function has finished, the event listener still has access to
those variables because of closure.
Example:
function setupButton() {
let count = 0; // outer variable
[Link]("myBtn").addEventListener("click", function () {
count++; // inner function uses outer variable
[Link]("Button clicked " + count + " times");
});
}
setupButton();
java script interview 31
🔹 Explanation:
setupButton() finishes execution. Normally, its variable count would be gone.
But the event listener’s callback still “remembers” count .
That’s closure! → The event listener invokes a closure every time you click.
🔹 2. Why should we remove unused Event Listeners?
Event listeners are powerful, but if you forget to remove them, they can cause
problems:
✅ Reasons to remove unused Event Listeners:
1. Memory Leaks 🧠💾
Every event listener keeps a reference to the DOM element and the
closure variables.
If the element is removed from the page but the event listener is still
attached → memory is not freed.
Over time, unused listeners build up → app becomes heavy.
2. Performance Issues ⚡
If you add many listeners but never remove them, the browser has to keep
checking each listener when the event occurs → slowing down your site.
3. Unexpected Behavior 🐞
If multiple listeners remain attached accidentally, you may see the same
event trigger multiple times → leading to bugs.
Example:
function addListener() {
const btn = [Link]("myBtn");
function handleClick() {
[Link]("Button clicked!");
java script interview 32
}
[Link]("click", handleClick);
// ❌ If we never remove this and delete btn from DOM later → memory leak!
// ✅ Correct way:
// [Link]("click", handleClick);
}
🎯 Summary
Event Listeners invoke closures because their callback functions can access
outer scope variables.
We should remove unused event listeners to prevent:
Memory leaks
Performance slowdowns
Unwanted repeated executions
📌TableJavaScript Array Methods – Summary
Modifies Returns New Array
Method Purpose (What it does)
Original? / Value?
forEach()
Runs a function for each
element
❌ No ❌ undefined
map()
Transforms each element,
returns new array
❌ No ✅ New Array
filter()
Keeps elements that match a
condition
❌ No ✅ New Array
java script interview 33
Modifies Returns New Array
Method Purpose (What it does)
Original? / Value?
reduce()
Reduces array to a single value
(sum, max, etc.)
❌ No ✅ Single Value
find()
Returns first element matching
❌ No ✅ Single Element /
condition undefined
findIndex() Returns index of first match ❌ No ✅ Index / -1
some()
Checks if at least one element
matches condition
❌ No ✅ Boolean
every()
Checks if all elements match
condition
❌ No ✅ Boolean
includes() Checks if array contains a value ❌ No ✅ Boolean
indexOf()
Finds index of a value (first
occurrence)
❌ No ✅ Index / -1
lastIndexOf()
Finds index of a value (last
occurrence)
❌ No ✅ Index / -1
sort()
Sorts array elements (default:
✅ Yes ✅ Same Array
string order) (sorted)
reverse() Reverses array order ✅ Yes ✅ Same Array
(reversed)
concat() Merges two or more arrays ❌ No ✅ New Array
slice()
Extracts part of array (non-
destructive)
❌ No ✅ New Array
splice()
Adds/removes/replaces
✅ Yes ✅ Removed
elements Elements Array
flat() Flattens nested arrays ❌ No ✅ New Array
flatMap() Maps + Flattens in one step ❌ No ✅ New Array
array destructing method is used to extract the elemants from an array and assign
them individullly variable
const arr = [10, 20, 30];
const [a, b, c] = arr;
java script interview 34
[Link](a); // 10
[Link](b); // 20
[Link](c); // 30
rest operator in destructing
const arr = [10, 20, 30, 40, 50];
const [first, second, ...rest] = arr;
[Link](first); // 10
[Link](second); // 20
[Link](rest); // [30, 40, 50]
#impotant
java script interview 35
Here’s a simple and clear explanation of the difference between HTML and DOM:
Feature HTML DOM (Document Object Model)
HTML (HyperText
Markup Language) is DOM is a programmatic representation of the
the code or markup that HTML document, created by the browser,
Definition
defines the structure which allows scripts (like JavaScript) to
and content of a access and manipulate the page.
webpage.
Static – it’s just
Dynamic – it’s an object-oriented
Nature text/code written in a
representation of the webpage in memory.
file.
Cannot be directly
Can be accessed and modified by JavaScript
manipulated by
Accessibility to change content, structure, and style
JavaScript; only exists
dynamically.
as markup.
Defines elements like
Provides an interface to interact with HTML
Purpose headings, paragraphs,
elements, attributes, and styles.
images, links, etc.
java script interview 36
Feature HTML DOM (Document Object Model)
Written in files and
Created by browser in memory as a tree of
Representation interpreted by browser
objects (nodes).
to render page.
[Link][0].textContent → "Hello
Example <p>Hello World</p>
World"
Basic DOM Questions
1. What is DOM?
Explain it as a tree-like representation of HTML elements created by the
browser, which allows JS to interact with the page.
2. Difference between HTML and DOM
Static markup vs dynamic object representation (explained in previous
table).
3. What is the difference between [Link] , getElementsByClassName ,
and querySelector ?
getElementById → single element by id.
getElementsByClassName → HTMLCollection of elements by class (live).
querySelector → first element matching CSS selector.
4. What is the difference between innerHTML , innerText , and textContent ?
innerHTML → returns HTML content (can include tags).
innerText → visible text only, respects CSS.
textContent → all text including hidden, no formatting.
5. What are the different ways to access DOM elements?
getElementById , getElementsByTagName , getElementsByClassName , querySelector ,
querySelectorAll .
DOM Manipulation Questions
1. How do you create, append, and remove DOM elements?
java script interview 37
[Link] , appendChild , removeChild / remove .
2. Difference between appendChild and append
appendChild → only accepts Node objects.
append → accepts Node objects or strings.
3. What is cloneNode and deep vs shallow clone?
cloneNode(true) → deep clone (all children copied).
cloneNode(false) → shallow clone (only parent element).
4. How do you change attributes of an element?
[Link]('attr', 'value')
[Link]('attr')
5. Difference between removeAttribute and [Link] = null
removeAttribute → completely removes the attribute.
[Link] = null → sets its value to null but attribute exists.
Event Handling Questions
1. How to add/remove events in DOM?
[Link]('click', callback)
[Link]('click', callback)
2. Difference between inline, HTML, and JS event handlers
Inline: <button onclick="func()">
HTML: using onclick property in JS
JS: addEventListener → preferred, supports multiple listeners
3. What is event bubbling and event capturing?
Bubbling → event propagates from child → parent
Capturing → event propagates from parent → child
Can be controlled by addEventListener(type, listener, useCapture)
java script interview 38
4. What is event delegation?
Attaching a single event listener to a parent to manage all its child events.
Reduces memory usage.
Advanced DOM Questions
1. What is the difference between live and static collections?
Live ( getElementsByClassName , getElementsByTagName ) → auto-updates if DOM
changes
Static ( querySelectorAll ) → doesn’t update automatically
2. What are the different node types in DOM?
Element Node, Text Node, Comment Node, Document Node,
DocumentFragment Node
3. How does the DOM tree relate to the HTML structure?
DOM tree mirrors the HTML, each tag → element node, text → text node
4. What is documentFragment and why is it used?
Lightweight container to append multiple elements at once. Improves
performance (avoids multiple reflows).
5. Difference between window and document objects
window → global object, represents the browser window
document → represents the web page content (DOM)
6. How to prevent default behavior and stop propagation?
[Link]() → prevents default action
[Link]() → stops bubbling or capturing
1. What is an event in JavaScript?
An event is an action or occurrence that happens in the browser, usually as a
result of user interaction or browser activity.
java script interview 39
Examples: click , keydown , mouseover , load .
2. What are the different types of events?
Mouse Events: click , dblclick , mouseenter , mouseleave , mousemove
Keyboard Events: keydown , keyup , keypress
Form Events: submit , change , focus , blur
Window Events: load , resize , scroll , unload
Touch Events (Mobile): touchstart , touchend , touchmove
3. How do you attach an event to an element?
Inline:
<button onclick="alert('Clicked')">Click Me</button>
DOM property:
const btn = [Link]('button');
[Link] = function() { alert('Clicked'); }
addEventListener (recommended):
[Link]('click', () => alert('Clicked'));
4. Difference between inline events and addEventListener:
Inline/Event Property addEventListener
Can assign only 1 handler at a time Can attach multiple handlers
Overwrites previous handler if reassigned Multiple handlers work independently
Harder to manage in large projects Recommended, flexible, and modern
java script interview 40
5. How do you remove an event listener?
You must pass the same function reference:
function clickHandler() { [Link]('Clicked'); }
[Link]('click', clickHandler);
[Link]('click', clickHandler);
6. What is the event object?
The event object is automatically passed to event handlers and contains
information about the event:
[Link] → element that triggered the event
[Link] → element that the handler is attached to
[Link] → type of event ( click , keydown )
[Link]() → prevents default browser action
[Link]() → stops event from bubbling/capturing
Event Propagation
7. What is event bubbling?
Event bubbling is when an event starts from the innermost element and
propagates upwards to parent elements.
[Link]('click', () => [Link]('Child'));
[Link]('click', () => [Link]('Parent'));
// Click on child → logs "Child" then "Parent"
8. What is event capturing?
Event capturing is the opposite of bubbling. The event starts from the outermost
parent and goes down to the target element.
java script interview 41
[Link]('click', () => [Link]('Parent'), true);
[Link]('click', () => [Link]('Child'), true);
// Click on child → logs "Parent" then "Child"
9. Difference between bubbling and capturing:
Event Bubbling Event Capturing
Inner → Outer Outer → Inner
Less commonly used, requires true in
Default behavior
addEventListener
stopPropagation() stops upward
stopPropagation() stops downward flow
flow
10. How do you control event propagation?
[Link]() → stops further propagation (both bubbling & capturing)
[Link]() → stops all other listeners on the same element
11. What is event delegation?
Event delegation is attaching one event listener to a parent element instead of
multiple child elements. It relies on event bubbling.
[Link]('#parent').addEventListener('click', (e) => {
if([Link] === 'BUTTON') alert('Button clicked!');
});
Advantages: Less memory usage, handles dynamically added elements.
12. Can you give an example of event delegation?
See the example above: attaching one listener to parent instead of each button
inside it.
java script interview 42
Advanced Event Handling
13. Difference between this and [Link] :
this → refers to the element the listener is attached to
[Link] → refers to the element that actually triggered the event
[Link]('click', function(e){
[Link](this); // divParent
[Link]([Link]); // clicked element inside divParent
});
14. What are passive event listeners?
Passive listeners improve scrolling performance. They tell the browser that the
listener won’t call preventDefault().
[Link]('scroll', () => [Link]('scroll'), { passive: true });
15. What is the once option in addEventListener?
once: true ensures the listener runs only once, then automatically removed.
[Link]('click', () => [Link]('Clicked once'), { once: true });
16. What is debouncing and throttling?
Debouncing: delays execution until user stops triggering the event.
Throttling: limits execution to once per interval, even if event fires many
times.
Used in scroll, resize, input events for performance.
17. How do you handle events for dynamically added elements?
java script interview 43
Use event delegation: attach listener to a parent container instead of the dynamic
element.
18. What are custom events?
Custom events allow you to create and dispatch your own events.
const myEvent = new CustomEvent('sayHello', { detail: { name: 'John' } });
[Link]('sayHello', (e) => [Link]([Link]));
[Link](myEvent); // logs "John"
Form and Window Events
19. How to handle form submission and prevent default?
[Link]('submit', (e) => {
[Link](); // prevents page reload
[Link]('Form submitted');
});
20. Common window events:
resize → window size changes
scroll → user scrolls page
load → page fully loaded
unload → page is unloaded
21. How to optimize performance for scroll/resize?
Use throttling or debouncing to reduce the number of times the handler executes.
Memory and Performance
22. Why remove unused event listeners?
java script interview 44
Listeners consume memory and may cause memory leaks if elements are
removed but listeners remain attached.
23. How do closures relate to event handlers?
Event handlers can remember variables from their outer function because of
closures:
function setup() {
let count = 0;
[Link]('click', () => {
count++;
[Link](count); // remembers count from setup
});
}
setup();
24. How to prevent memory leaks with event listeners?
Remove listeners when not needed
Avoid creating listeners in loops without proper cleanup
Use event delegation
Browser API and Event Loop
25. How are event listeners handled internally?
Stored in browser Web API environment
Triggered events go to callback queue
Event loop checks stack and executes when call stack is empty
26. Difference between synchronous and asynchronous event handling:
Synchronous: executes immediately (e.g., onclick inline alert)
Asynchronous: queued in callback queue (e.g., setTimeout , fetch )
java script interview 45
27. How does event loop interact with events like click/setTimeout?
Event occurs → browser Web API handles it
Callback placed in callback queue
Event loop moves it to call stack when empty → executed
java script interview 46