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
Answer: C. If x is not found in array a, the function returns -1.
The function iterates through array a and returns i+1 (the 1-based position) when x is found. If the loop completes without finding x, it returns -1. Option A is incorrect because an empty array causes the for loop condition to be false immediately, so no abnormal termination occurs. Option B is incorrect because the function returns immediately upon finding the first occurrence, not all occurrences.
Step-by-step Derivation:
Trace the function logic:
- If a = [] and x = 5: The loop condition i < 0 is false, so the loop never executes. The function reaches return -1 and exits normally.
- If a = [1, 2, 3, 2, 4] and x = 2: On iteration i=1, a[1]==2 is true, so the function returns 1+1=2 and exits. The second occurrence at i=3 is never checked.
- If a = [1, 3, 5] and x = 7: The loop completes all iterations without finding a match, and return -1 is executed.
Therefore, statement C is correct.