The following JavaScript function searches for a number among integers: Choose the correct...
Accenture technical mcq question, verified with a worked answer. Free to practise - no sign-up.
The following JavaScript function searches for a number among integers:
function find(x, a) {
for (let i = 0; i < a.length; i++) {
if (a[i] == x) {
return i + 1;
}
}
return -1;
}
Choose the correct statement regarding this function:
Show answer & explanation
Option A is correct. The function iterates through the array and returns -1 if no match is found (line 6). Option B is incomplete (missing return value description). Option C is false: an empty array causes the loop condition i < a.length to be false immediately, so no abnormal termination occurs—the function simply returns -1. Therefore, D is also incorrect.
Step-by-step Derivation:
Trace execution:
Element not found: Loop runs through all indices without matching; reaches line 6 and returns -1. ✓ A is correct.
Multiple occurrences: Loop encounters first match at some index i, returns
i + 1immediately. Remaining occurrences are never checked. B is incomplete/misleading.Empty array (a = []):
- a.length = 0
- Loop condition:
0 < 0is false - Loop never executes
- Returns -1 normally (no crash)
- C is false.
Since A is correct, D is false.