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)
- It is not possible for the webpage to start rendering before loading the JS files, as long as
<script>is in<head> - This problem can be fixed by using
asyncon both<script>tags - This problem can be fixed by using
deferon both<script>tags - This problem can be fixed by using
asyncfor file1.js anddeferfor file2.js - This problem can be fixed by using
deferfor file1.js andasyncfor file2.js
Answer
Answer: Option 3 only
async: parallel download, executes immediately when ready, order NOT guaranteeddefer: parallel download, executes after HTML parsing, order preserved- ❌ Option 1: Both async and defer allow rendering to proceed
- ❌ Option 2:
asyncon both doesn’t guarantee order - ✅ Option 3:
deferon both - no render blocking + order preserved - ❌ Option 4:
asyncon file1 could execute after file2 (defer) - ❌ Option 5:
asyncon 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)
$("#abc")document.getElementByClass("def")document.getElementById("#abc")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)
- More than 1000ms but less than 3000ms after setTimeout
- Exactly 2000ms after setTimeout
- More than 1999ms but less than 2001ms after setTimeout
- More than 2000ms but less than 2001ms after setTimeout
- 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,
fcan be delayed well beyond 2000ms
Q5 - Noscript
The <noscript> tag: (Select closest option)
- Is executed when the
<script>tag is empty - Is used to programmatically turn off script execution on a webpage
- Is executed when the page is loaded with scripts disabled
- Was used in IE6 and older browsers, no longer supported by newer browsers
- 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)
- Error: X is read-only
- Error: X.a is already defined
- It will print 1
- It will print 3
- It will print undefined
Answer
Answer: Option 4 - prints 3
constprevents reassignment ofXitself, not mutation of its propertiesX.a = 3is 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)
- Compilation error
- Prints
123 - Prints
123foo - Prints
012foo - Prints
foo012
Answer
Answer: Option 2 - prints 123
for...ofiterates only indexed elements (1, 2, 3), not custom propertiesa.x = "foo"is skipped entirelyb = "" + 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)
- Compilation error
- ReferenceError: b is not defined (or similar)
- Prints Yes
- Prints No
- Prints undefined
Answer
Answer: Option 2 - ReferenceError
letis block-scoped - both declarations are inside{ }blocksbdoes not exist outside the if/else blocks- With
varthis 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)
- After 3 seconds, first, second, and done are all printed together
- done is printed immediately. After 3 seconds first is printed. After 3 more seconds second is printed.
- done is printed immediately. After 3 seconds, first and second are both printed together.
- After 3 seconds, first is printed. After 3 more seconds, second and done are printed together.
- done is printed immediately. 6 seconds later, first and second are both printed together.
Answer
Answer: Option 1
- Both
p1andp2timers start concurrently before anyawait await p1pauses ~3 seconds → printsfirstawait p2is already resolved by then → printssecondalmost instantlyconsole.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)
- The first argument of ReactDOM.render must be a JavaScript object, not HTML/JSX
- The second argument must be
document.getElementById('root') - The function attr should return a string or JS object, not HTML/JSX
attrneeds to be capitalized asAttr- 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
Attrand 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)
- First time MyComp is called, it will print
cnt is 3 - Second time MyComp is called, it will print
cnt is 6 - First time MyComp is called, it will print
cnt is 1 - First time MyComp is called, it will print
cnt is 2 - 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)
- The doClick function should return
true - The onClick attribute should be
onClick="doClick(); return false;" - The doClick function should call
e.preventDefault()instead of returning false - Replace
href={someUrl}withhref="#" - None of the above
Answer
Answer: Option 3
- In React,
return falsedoes 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)
- Using
this.parent.rupees.setState - Using
this.parent.rupees.state.amount - Using
this.getParent().getChildren()[0].setState - Using
window.Money.rupees.setState - 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.Moneyare 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)
ReactDOM.update(counter_var, document.GetElementByID('counter'))ReactDOM.render(counter_var, document.GetElementByID('counter'))ReactDOM.render(counter_html(), document.getElementById('root'));$('#counter').update(counter_var)- This cannot be done without modifying counter_html
Answer
Answer: Option 3
counter_html()is called fresh each time, reading the updatedcounter_varReactDOM.renderdiffs new VDOM against previous - only updates the changed node- React’s reconciliation handles the efficiency, no need to target
#counterdirectly - 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” ✓