Q12 /20 The following JavaScript function returns the number where the integer x occurs in...
Accenture technical mcq question, verified with a worked answer. Free to practise - no sign-up.
The following JavaScript function returns the number where the integer x occurs in the given array of integers a.
function find(a, x) {
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
The function uses a linear search that returns the 1-indexed position of the first occurrence of x, or -1 if not found. Option C is correct: when the loop completes without finding x, the function explicitly returns -1. Option A is false because an empty array simply causes the loop condition i < 0 to be false on the first iteration, returning -1 without error. Option B is false because the function returns immediately upon finding the first match, so only one occurrence is ever returned.
Step-by-step Derivation:
Trace through the function logic:
- If
ais empty (length 0): Loop conditioni < a.lengthevaluates to0 < 0 = false. Loop skips. Function returns-1. No abnormal termination. - If
xhas multiple matches: Thereturnstatement inside theifblock terminates the function immediately when the first match is found at indexi. Subsequent occurrences are never checked. - If
xis not found: The loop completes all iterations without entering theifblock. After the loop ends, the function reachesreturn -1;and returns-1.
Therefore, only statement C is correct.