Tricky MCQs Part 4
Section 1: JavaScript Web
Q1 - Event Bubbling
Consider the following code:
document.getElementById('outer').addEventListener('click', () => console.log('outer'));
document.getElementById('inner').addEventListener('click', (e) => {
console.log('inner');
e.stopPropagation();
});Where #inner is a button inside #outer. When the button is clicked, what is logged?
outertheninnerinnerthenouterinneronlyouteronly- Nothing is logged
Answer
Answer: Option 3 - inner only
- Events bubble from child to parent by default
e.stopPropagation()stops the event from bubbling up to#outer- So
outer’s listener never fires
Q2 - Closure in a Loop
for (var i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 0);
}What is logged?
0,1,20,0,03,3,31,2,3undefined,undefined,undefined
Answer
Answer: Option 3 - 3, 3, 3
varis function-scoped, not block-scoped- All three callbacks share the same
ivariable - By the time the callbacks fire, the loop has finished and
iis3 - Fix: use
letinstead ofvar
Q3 - Fetch and HTTP Errors
fetch('https://api.example.com/data')
.then((response) => response.json())
.then((data) => console.log(data))
.catch((err) => console.log('Error:', err));The server returns a 404 response with a valid JSON body. What happens?
.catch()is triggered because the server returned 404console.log(data)is called withnull.then(response => response.json())is called normally and.catch()is NOT triggered- The fetch Promise rejects immediately for any non-2xx status
response.json()throws a SyntaxError
Answer
Answer: Option 3
fetch()only rejects on network failures, not HTTP error statuses- A 404 still resolves the promise -
response.okwould be false but the chain continues .catch()won’t trigger unlessresponse.json()itself throws (e.g. non-JSON body)- Always check
response.okmanually if you want to handle HTTP errors
Q4 - Microtasks vs Macrotasks
console.log('A');
setTimeout(() => console.log('B'), 0);
Promise.resolve().then(() => console.log('C'));
console.log('D');What is the output?
A,B,C,DA,D,B,CA,D,C,BA,C,D,BA,B,D,C
Answer
Answer: Option 3 - A, D, C, B
- Synchronous code runs first:
A,D - Microtask queue (Promises) runs before macrotask queue:
C - Macrotask queue (setTimeout) runs last:
B
Q5 - Event Delegation
You have a <ul> with 1000 dynamically generated <li> items. You want to log the text of whichever <li> is clicked. Which is the most correct and efficient approach?
- Add a click listener to each
<li>usingquerySelectorAll('li').forEach(...) - Add a click listener to the
<ul>and useevent.targetto identify the clicked<li> - Add a click listener to
document.bodyand useevent.currentTarget - Add a click listener to
documentand checkevent.srcElement - Options 1 and 4 are equivalent in performance
Answer
Answer: Option 2 - Event Delegation
- One listener on the parent
<ul>usingevent.targethandles all children - Much more efficient than attaching 1000 individual listeners
- Also works for dynamically added
<li>items added after the listener is set up event.currentTarget(Option 3) refers to the element the listener is attached to, not the clicked element
Section 2: ECMAScript 6
Q6 - Arrow Functions and this
const obj = {
name: 'Shan',
greet: () => {
console.log('Hello ' + this.name);
},
};
obj.greet();What is logged? (Assume strict mode / ES module context)
Hello ShanHello undefinedTypeError: cannot read property 'name' of undefinedHello(empty string)ReferenceError: this is not defined
Answer
Answer: Option 2 - Hello undefined
- Arrow functions do NOT have their own
this - They inherit
thisfrom the enclosing lexical scope, which here is the module scope, notobj this.nameisundefinedin strict mode- Fix: use a regular function expression -
greet: function() { ... }
Q7 - Destructuring with Defaults
const { a, b = 10, c } = { a: 1, b: undefined, c: null };
console.log(a, b, c);What is logged?
1,10,null1,undefined,null1,10,undefined1,undefined,undefined- Error: cannot destructure
Answer
Answer: Option 1 - 1, 10, null
- Default values in destructuring only activate when the value is
undefined, notnull bisundefined→ uses default10cisnull→ staysnull, default does not apply
Q8 - Spread and Shallow Copy
const a = [{ x: 1 }, { x: 2 }];
const b = [...a];
b[0].x = 99;
console.log(a[0].x, b[0].x);What is logged?
1,9999,991,199,1- Error: cannot mutate spread array
Answer
Answer: Option 2 - 99, 99
- Spread creates a shallow copy - the array is new but the objects inside are the same references
- Mutating
b[0].xalso mutatesa[0].xbecause they point to the same object - A deep copy would be needed to avoid this:
JSON.parse(JSON.stringify(a))
Q9 - Promise.all
const p1 = Promise.resolve(1);
const p2 = Promise.reject('error');
const p3 = Promise.resolve(3);
Promise.all([p1, p2, p3])
.then((values) => console.log(values))
.catch((err) => console.log(err));What is logged?
[1, 'error', 3][1, 3]error[1, undefined, 3]- Nothing is logged
Answer
Answer: Option 3 - error
Promise.allrejects immediately if any single promise rejects (fail-fast)- The
.catch()block fires with the rejection reason - Use
Promise.allSettledif you want all results regardless of failures
Q10 - Optional Chaining and Nullish Coalescing
const user = { profile: { name: 'Shan' } };
const city = user?.address?.city ?? 'Unknown';
const name = user?.profile?.name ?? 'Anonymous';
console.log(city, name);What is logged?
undefined,ShanUnknown,AnonymousUnknown,ShanTypeError: cannot read property 'city' of undefinednull,Shan
Answer
Answer: Option 3 - Unknown, Shan
user?.addressisundefined→undefined?.cityisundefinedundefined ?? 'Unknown'→'Unknown'(nullish coalescing triggers onnull/undefined)user?.profile?.name→'Shan'→'Shan' ?? 'Anonymous'→'Shan'(non-nullish, right side ignored)
Section 3: React.js (Functional Components)
Q11 - useEffect Dependency Array
function UserProfile({ userId }) {
const [user, setUser] = useState(null);
useEffect(() => {
fetch(`/api/users/${userId}`)
.then((res) => res.json())
.then((data) => setUser(data));
}, []);
return <div>{user?.name}</div>;
}What is the problem with this code?
useEffectcannot contain fetch callssetUsercannot be called insideuseEffect- The empty dependency array means the effect only runs on mount and won’t re-fetch when
userIdchanges - This will cause an infinite re-render loop
- There is no problem
Answer
Answer: Option 3
- Empty
[]means the effect runs only once on mount - If
userIdprop changes, the component re-renders but the fetch does NOT re-run - Fix: add
userIdto the dependency array:[userId]
Q12 - useState Stale Closure
function Counter() {
const [count, setCount] = useState(0);
function handleClick() {
setCount(count + 1);
setCount(count + 1);
setCount(count + 1);
}
return <button onClick={handleClick}>{count}</button>;
}After clicking the button once, what does the counter show?
3102- Throws an error
Answer
Answer: Option 2 - 1
- All three
setCount(count + 1)calls use the same stalecountvalue (0), so all set it to 1 - React batches them but they all resolve to the same value
- Fix: use the functional update form
setCount(prev => prev + 1)- this increments from the latest state each time
Q13 - React.memo and useCallback
function Parent() {
const [count, setCount] = useState(0);
const handleClick = () => console.log('clicked');
return (
<>
<button onClick={() => setCount(count + 1)}>Increment</button>
<Child onClick={handleClick} />
</>
);
}
const Child = React.memo(({ onClick }) => {
console.log('Child rendered');
return <button onClick={onClick}>Click Child</button>;
});What happens every time the Increment button is clicked?
- Only Parent re-renders, Child does not re-render because of
React.memo - Both Parent and Child re-render because
handleClickis a new reference on every render - Only Child re-renders
- Neither re-renders because state updates are batched
- Child re-renders only on the first click
Answer
Answer: Option 2
React.memodoes a shallow prop comparisonhandleClickis redeclared as a new function reference on every Parent render- New reference →
React.memosees a changed prop → Child re-renders - Fix: wrap
handleClickwithuseCallback(() => console.log('clicked'), [])to stabilize the reference
Q14 - useRef vs useState
function Timer() {
const [count, setCount] = useState(0);
const intervalRef = useRef(null);
function start() {
intervalRef.current = setInterval(() => setCount((c) => c + 1), 1000);
}
function stop() {
clearInterval(intervalRef.current);
}
return (
<>
<p>{count}</p>
<button onClick={start}>Start</button>
<button onClick={stop}>Stop</button>
</>
);
}Which statements are true about useRef here? (Pick all that apply)
- Changing
intervalRef.currenttriggers a re-render intervalRef.currentpersists across renders without causing re-rendersuseRefcould be replaced withuseStatehere with no side effectsintervalRef.currentresets tonullon every re-render- This is the correct pattern for storing mutable values that should not trigger re-renders
Answer
Answer: Options 2 and 5
useRefstores a mutable value that persists across renders but does NOT trigger re-renders when changed- If you used
useStatefor the interval ID, everysetIntervalId()call would cause an unnecessary re-render - The ref’s value survives re-renders, unlike a regular variable declared inside the component
Q15 - Rules of Hooks in a Custom Hook
function useData(url) {
const [data, setData] = useState(null);
if (url) {
useEffect(() => {
fetch(url)
.then((r) => r.json())
.then(setData);
}, [url]);
}
return data;
}What is wrong with this custom hook?
- Custom hooks cannot use
useEffect useEffectis called conditionally inside anifblock, violating Rules of HookssetDatacannot be passed directly as a.then()callback- Custom hooks must return an object, not a primitive or
null - Nothing is wrong, this is valid
Answer
Answer: Option 2
- Rules of Hooks: hooks must not be called inside conditions, loops, or nested functions
- If
urlchanges from truthy to falsy between renders,useEffectmay or may not be called, breaking React’s internal hook call order - Fix: move the condition inside
useEffect:
useEffect(() => {
if (url) {
fetch(url)
.then((r) => r.json())
.then(setData);
}
}, [url]);