Tricky MCQs Part 3

Section 1: JavaScript Web


Q1 - JavaScript in Head (async vs defer)

Two scripts are in <head>: file1.js and file2.js. file2.js depends on file1.js. Loading them is slowing down rendering. The HTML can render without JS (fallbacks exist). Which statements are true? (Pick all that apply)

  1. It is not possible for the webpage to start rendering before loading the JS files, as long as <script> is in <head>
  2. This problem can be fixed by using async on both <script> tags
  3. This problem can be fixed by using defer on both <script> tags
  4. This problem can be fixed by using async for file1.js and defer for file2.js
  5. This problem can be fixed by using defer for file1.js and async for file2.js
Answer

Answer: Option 3 only

  • async: parallel download, executes immediately when ready, order NOT guaranteed
  • defer: parallel download, executes after HTML parsing, order preserved
  • ❌ Option 1: Both async and defer allow rendering to proceed
  • ❌ Option 2: async on both doesn’t guarantee order
  • ✅ Option 3: defer on both - no render blocking + order preserved
  • ❌ Option 4: async on file1 could execute after file2 (defer)
  • ❌ Option 5: async on file2 could fire before file1 resolves

Q2 - JavaScript Selector

Consider <div id="abc" class="def">xyz</div>. Which is the correct way to select this element using pure JavaScript? (Select closest option)

  1. $("#abc")
  2. document.getElementByClass("def")
  3. document.getElementById("#abc")
  4. document.getElementById("abc")
Answer

Answer: Option 4

  • ❌ $("#abc"): jQuery, not pure JS
  • ❌ document.getElementByClass("def"): wrong method name + returns a collection
  • ❌ document.getElementById("#abc"): should not include #
  • ✅ document.getElementById("abc"): correct syntax, selects unique element

Q3 - Async Callback (doStuff)

doStuff(callback) is an async function that calls callback(results, err). If error, err is non-null. Consider:

console.log('A');
doStuff((results, err) => {
  if (err) {
    console.log('B');
  }
  console.log('C');
});
console.log('D');

Which output sequences can NEVER be produced? (Pick all that apply)

  • A B C D
  • A C D
  • A D C
  • A D B C
  • None of the above
Answer

Answer: A B C D and A C D can NEVER be produced

  • D always logs synchronously before the callback ever fires
  • ❌ A B C D: D cannot come after B/C
  • ❌ A C D: D cannot come after C
  • ✅ A D C: Possible - no error case
  • ✅ A D B C: Possible - error case

Q4 - setTimeout

Consider setTimeout(f, 2000). Which statement most accurately describes when f is guaranteed to be called? (Select closest option)

  1. More than 1000ms but less than 3000ms after setTimeout
  2. Exactly 2000ms after setTimeout
  3. More than 1999ms but less than 2001ms after setTimeout
  4. More than 2000ms but less than 2001ms after setTimeout
  5. More than 2000ms after setTimeout - but there is no guarantee of how much more
Answer

Answer: Option 5

  • setTimeout(f, 2000) is a minimum delay, not an exact one
  • Callback only runs when the call stack is empty
  • If the main thread is busy, f can be delayed well beyond 2000ms

Q5 - Noscript

The <noscript> tag: (Select closest option)

  1. Is executed when the <script> tag is empty
  2. Is used to programmatically turn off script execution on a webpage
  3. Is executed when the page is loaded with scripts disabled
  4. Was used in IE6 and older browsers, no longer supported by newer browsers
  5. Was used with HTML4.0, no longer supported by HTML5
Answer

Answer: Option 3

  • <noscript> renders fallback content when JS is disabled or unsupported
  • Still valid and fully supported in HTML5

Section 2: ECMAScript 6


Q6 - ES6 const

const X = { a: 1, b: 2 };
X.a = 3;
console.log(X.a);

What is the result? (Select closest option)

  1. Error: X is read-only
  2. Error: X.a is already defined
  3. It will print 1
  4. It will print 3
  5. It will print undefined
Answer

Answer: Option 4 - prints 3

  • const prevents reassignment of X itself, not mutation of its properties
  • X.a = 3 is valid → prints 3

Q7 - ES6 for..of

let a = [1, 2, 3];
a.x = 'foo';
let b = '';
for (i of a) {
  b += i;
}
console.log(b);

What is the result? (Select closest option)

  1. Compilation error
  2. Prints 123
  3. Prints 123foo
  4. Prints 012foo
  5. Prints foo012
Answer

Answer: Option 2 - prints 123

  • for...of iterates only indexed elements (1, 2, 3), not custom properties
  • a.x = "foo" is skipped entirely
  • b = "" + 1 + 2 + 3 = "123" (string concatenation)

Q8 - ES6 Let

var a = 10;
if (a < 20) {
  let b = 'Yes';
} else {
  let b = 'No';
}
console.log(b);

What is the result? (Select closest option)

  1. Compilation error
  2. ReferenceError: b is not defined (or similar)
  3. Prints Yes
  4. Prints No
  5. Prints undefined
Answer

Answer: Option 2 - ReferenceError

  • let is block-scoped - both declarations are inside { } blocks
  • b does not exist outside the if/else blocks
  • With var this would work fine (function-scoped)

Q9 - Promises with async/await

var async_f = async function () {
  var p1 = promised_function('first');
  var p2 = promised_function('second');
  console.log(await p1);
  console.log(await p2);
  console.log('done');
};
async_f();

Where promised_function resolves after 3 seconds. What happens? (Select closest option)

  1. After 3 seconds, first, second, and done are all printed together
  2. done is printed immediately. After 3 seconds first is printed. After 3 more seconds second is printed.
  3. done is printed immediately. After 3 seconds, first and second are both printed together.
  4. After 3 seconds, first is printed. After 3 more seconds, second and done are printed together.
  5. done is printed immediately. 6 seconds later, first and second are both printed together.
Answer

Answer: Option 1

  • Both p1 and p2 timers start concurrently before any await
  • await p1 pauses ~3 seconds → prints first
  • await p2 is already resolved by then → prints second almost instantly
  • console.log('done') fires right after
  • All three print at the ~3 second mark

Section 3: React.js (Functional Components)


Q10 - React.js Error

function attr(props) {
  return <div>The value is {props.value}</div>;
}
ReactDOM.render(<attr value="v1" />, document.getElementById('mydiv'));

This code has an error. What is the problem? (Pick all that apply)

  1. The first argument of ReactDOM.render must be a JavaScript object, not HTML/JSX
  2. The second argument must be document.getElementById('root')
  3. The function attr should return a string or JS object, not HTML/JSX
  4. attr needs to be capitalized as Attr
  5. None of the above
Answer

Answer: Option 4

  • JSX treats lowercase names as native HTML elements
  • <attr .../> is treated as an unknown HTML tag, not the function
  • Fix: rename to Attr and use <Attr value="v1"/>

Q11 - useState #3

function MyComp() {
  for (let i = 0; i < 3; i++) {
    const [cnt, setCnt] = useState(i);
  }
  setCnt(cnt + 1);
  console.log('cnt is ' + cnt);
}

Which statement is true? (Pick all that apply)

  1. First time MyComp is called, it will print cnt is 3
  2. Second time MyComp is called, it will print cnt is 6
  3. First time MyComp is called, it will print cnt is 1
  4. First time MyComp is called, it will print cnt is 2
  5. This is illegal because useState cannot be used in a for loop
Answer

Answer: Option 5 only

  • Violates React’s Rules of Hooks: hooks must not be called inside loops
  • Hook call order must be consistent across every render
  • React will throw a rules-of-hooks violation at runtime

Q12 - React preventDefault

function eventAction() {
  function doClick(e) {
    // click processing
    return false;
  }
  return (
    <a href={someUrl} onClick={doClick}>
      My button
    </a>
  );
}

return false is not preventing the default navigation. What is the recommended fix? (Select closest option)

  1. The doClick function should return true
  2. The onClick attribute should be onClick="doClick(); return false;"
  3. The doClick function should call e.preventDefault() instead of returning false
  4. Replace href={someUrl} with href="#"
  5. None of the above
Answer

Answer: Option 3

  • In React, return false does nothing to prevent default behavior
  • React’s synthetic event system requires e.preventDefault() explicitly

Q13 - Sibling State

Component Money has two children: Rupees and Paisa, both with an amount state. You need addPaisa(amt) in Paisa to increment Paisa’s amount, and if total > 100, decrement it by 100 and increment Rupees’ amount by 1. What is the right way for addPaisa in Paisa to access Rupees’ state? (Select closest option)

  1. Using this.parent.rupees.setState
  2. Using this.parent.rupees.state.amount
  3. Using this.getParent().getChildren()[0].setState
  4. Using window.Money.rupees.setState
  5. It is not possible for a component to access a sibling component’s state
Answer

Answer: Option 5

  • State is private and local to the component that owns it
  • Correct pattern: lift state up to parent Money, pass state and update callback as props
  • this.parent, this.getParent(), window.Money are not valid React APIs

Q14 - Counter HTML

counter_var = 1;
function counter_html() {
  return (
    <div>
      <h1>Counter</h1>
      <h2>
        The count is: <span id="counter">{counter_var}</span>
      </h2>
    </div>
  );
}
var element = counter_html();
ReactDOM.render(element, document.getElementById('root'));

function counter_update() {
  counter_var += 1;
  // ?????
}
setInterval(counter_update, 1000);

What code should replace // ????? to efficiently update only the counter span every second? (Select closest option)

  1. ReactDOM.update(counter_var, document.GetElementByID('counter'))
  2. ReactDOM.render(counter_var, document.GetElementByID('counter'))
  3. ReactDOM.render(counter_html(), document.getElementById('root'));
  4. $('#counter').update(counter_var)
  5. This cannot be done without modifying counter_html
Answer

Answer: Option 3

  • counter_html() is called fresh each time, reading the updated counter_var
  • ReactDOM.render diffs new VDOM against previous - only updates the changed node
  • React’s reconciliation handles the efficiency, no need to target #counter directly
  • Options 1 and 4 use non-existent APIs

Section 4: Coding


Q15 - Expensive Service

Given a JSON string like:

[
  ["Swiggy", 123],
  ["Swiggy", 227],
  ["Zomato", 103],
  ["Zomato", 171],
  ["Dunzo", 131],
  ["Zomato", 122],
  ["Swiggy", 181]
]

Write a JavaScript function that takes such a string and returns the name of the service with the highest average payment. For the above input, it should return “Swiggy”. Aim for O(n) time complexity.

Answer
// Time complexity: O(n)
function mostExpensiveService(jsonString) {
  const payments = JSON.parse(jsonString);
  const map = new Map();

  for (let i = 0; i < payments.length; i++) {
    const service = payments[i][0];
    const amount = payments[i][1];
    if (!map.has(service)) {
      map.set(service, { total: 0, count: 0 });
    }
    map.get(service).total += amount;
    map.get(service).count += 1;
  }

  let bestService = null;
  let bestAverage = Number.NEGATIVE_INFINITY;

  for (const [service, data] of map) {
    const avg = data.total / data.count;
    if (avg > bestAverage) {
      bestAverage = avg;
      bestService = service;
    }
  }

  return bestService;
}
  • Swiggy: (123 + 227 + 181) / 3 = 177
  • Zomato: (103 + 171 + 122) / 3 = 132
  • Dunzo: 131 / 1 = 131

Returns “Swiggy” ✓