The following JavaScript function returns the number where the integer x occurs in the...
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 iterates through the array and returns i + 1 (1-indexed position) when x is found. If the loop completes without finding x, it explicitly returns -1. Option A is false because an empty array causes the loop condition i < a.length to fail immediately (0 < 0 is false), so execution continues to return -1 without error. Option B is false because the function returns immediately upon finding the first occurrence, so only one position is ever returned.
Step-by-step Derivation:
Trace through each option:
Option A: Empty array (length 0)
- Loop:
for (let i = 0; i < 0; i++)→ condition is false immediately - Loop does not execute
- Function reaches
return -1normally - No abnormal termination ✗
Option B: Array [1, 2, 2, 3], searching for x = 2
- i=0:
a[0](1) ≠ 2, continue - i=1:
a[1](2) == 2,return 1 + 1 = 2→ function exits - Second occurrence at i=2 is never reached
- Does not return all occurrences ✗
Option C: Array [1, 2, 3], searching for x = 5
- Loop runs: i=0,1,2; no matches found
- Loop exits when i=3
- Reaches
return -1✓
Option C is correct.