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
Option C is correct. When x is not found in the array, the loop completes without returning, and the function executes return -1;. Option A is false because an empty array (length 0) causes the loop condition i < a.length to be false immediately, so the function safely returns -1 with no error. Option B is false because the function uses return inside the loop, which exits immediately upon finding the first occurrence, not all occurrences.
Step-by-step Derivation:
Trace through each option:
Option A: Empty array (a.length = 0)
- Loop condition:
0 < 0→ false - Loop never executes
- Executes
return -1; - No abnormal termination; returns -1 normally. FALSE.
Option B: Array with multiple occurrences (e.g., a = [5, 3, 5], x = 5)
- i = 0: a[0] = 5 == x → return 0 + 1 = 1 (exits immediately)
- Function never reaches the second 5
- Only first occurrence is returned, not all. FALSE.
Option C: Element not found (e.g., a = [1, 2, 3], x = 4)
- Loop runs for i = 0, 1, 2; no match found
- Loop exits normally
- Executes
return -1; - TRUE.