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 when x is found (1-based indexing), or -1 if the loop completes without finding a match. Option C is correct because the function explicitly returns -1 after the loop ends if no match is found. Option A is incorrect because an empty array simply results in the loop condition being false, returning -1 normally. Option B is incorrect because the function returns immediately upon finding the first occurrence, so it cannot return all occurrences.
Step-by-step Derivation:
Trace through the function logic:
- If
a.length === 0, the for loop conditioni < a.lengthis false from the start, so the loop body never executes. - The function then reaches
return -1;and exits normally (no error). - If
xexists in the array at indexi, the function returnsi + 1and exits immediately. - If
xis never found after checking all elements, the loop ends andreturn -1;executes. - Therefore: A is false (no abnormal termination), B is false (only first occurrence returned), C is true (returns -1 when not found).