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?

  1. outer then inner
  2. inner then outer
  3. inner only
  4. outer only
  5. 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?

  1. 0, 1, 2
  2. 0, 0, 0
  3. 3, 3, 3
  4. 1, 2, 3
  5. undefined, undefined, undefined
Answer

Answer: Option 3 - 3, 3, 3

  • var is function-scoped, not block-scoped
  • All three callbacks share the same i variable
  • By the time the callbacks fire, the loop has finished and i is 3
  • Fix: use let instead of var

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?

  1. .catch() is triggered because the server returned 404
  2. console.log(data) is called with null
  3. .then(response => response.json()) is called normally and .catch() is NOT triggered
  4. The fetch Promise rejects immediately for any non-2xx status
  5. 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.ok would be false but the chain continues
  • .catch() won’t trigger unless response.json() itself throws (e.g. non-JSON body)
  • Always check response.ok manually 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?

  1. A, B, C, D
  2. A, D, B, C
  3. A, D, C, B
  4. A, C, D, B
  5. A, 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?

  1. Add a click listener to each <li> using querySelectorAll('li').forEach(...)
  2. Add a click listener to the <ul> and use event.target to identify the clicked <li>
  3. Add a click listener to document.body and use event.currentTarget
  4. Add a click listener to document and check event.srcElement
  5. Options 1 and 4 are equivalent in performance
Answer

Answer: Option 2 - Event Delegation

  • One listener on the parent <ul> using event.target handles 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)

  1. Hello Shan
  2. Hello undefined
  3. TypeError: cannot read property 'name' of undefined
  4. Hello (empty string)
  5. ReferenceError: this is not defined
Answer

Answer: Option 2 - Hello undefined

  • Arrow functions do NOT have their own this
  • They inherit this from the enclosing lexical scope, which here is the module scope, not obj
  • this.name is undefined in 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. 1, 10, null
  2. 1, undefined, null
  3. 1, 10, undefined
  4. 1, undefined, undefined
  5. Error: cannot destructure
Answer

Answer: Option 1 - 1, 10, null

  • Default values in destructuring only activate when the value is undefined, not null
  • b is undefined → uses default 10
  • c is null → stays null, 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. 1, 99
  2. 99, 99
  3. 1, 1
  4. 99, 1
  5. 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].x also mutates a[0].x because 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. [1, 'error', 3]
  2. [1, 3]
  3. error
  4. [1, undefined, 3]
  5. Nothing is logged
Answer

Answer: Option 3 - error

  • Promise.all rejects immediately if any single promise rejects (fail-fast)
  • The .catch() block fires with the rejection reason
  • Use Promise.allSettled if 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?

  1. undefined, Shan
  2. Unknown, Anonymous
  3. Unknown, Shan
  4. TypeError: cannot read property 'city' of undefined
  5. null, Shan
Answer

Answer: Option 3 - Unknown, Shan

  • user?.address is undefined → undefined?.city is undefined
  • undefined ?? 'Unknown' → 'Unknown' (nullish coalescing triggers on null / 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?

  1. useEffect cannot contain fetch calls
  2. setUser cannot be called inside useEffect
  3. The empty dependency array means the effect only runs on mount and won’t re-fetch when userId changes
  4. This will cause an infinite re-render loop
  5. There is no problem
Answer

Answer: Option 3

  • Empty [] means the effect runs only once on mount
  • If userId prop changes, the component re-renders but the fetch does NOT re-run
  • Fix: add userId to 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?

  1. 3
  2. 1
  3. 0
  4. 2
  5. Throws an error
Answer

Answer: Option 2 - 1

  • All three setCount(count + 1) calls use the same stale count value (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?

  1. Only Parent re-renders, Child does not re-render because of React.memo
  2. Both Parent and Child re-render because handleClick is a new reference on every render
  3. Only Child re-renders
  4. Neither re-renders because state updates are batched
  5. Child re-renders only on the first click
Answer

Answer: Option 2

  • React.memo does a shallow prop comparison
  • handleClick is redeclared as a new function reference on every Parent render
  • New reference → React.memo sees a changed prop → Child re-renders
  • Fix: wrap handleClick with useCallback(() => 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)

  1. Changing intervalRef.current triggers a re-render
  2. intervalRef.current persists across renders without causing re-renders
  3. useRef could be replaced with useState here with no side effects
  4. intervalRef.current resets to null on every re-render
  5. This is the correct pattern for storing mutable values that should not trigger re-renders
Answer

Answer: Options 2 and 5

  • useRef stores a mutable value that persists across renders but does NOT trigger re-renders when changed
  • If you used useState for the interval ID, every setIntervalId() 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?

  1. Custom hooks cannot use useEffect
  2. useEffect is called conditionally inside an if block, violating Rules of Hooks
  3. setData cannot be passed directly as a .then() callback
  4. Custom hooks must return an object, not a primitive or null
  5. 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 url changes from truthy to falsy between renders, useEffect may 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]);