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 the 1-indexed position when x is found. If the loop completes without finding x, the function returns -1. Option A is false because an empty array simply causes the loop condition to fail immediately (i = 0; i < 0 is false), and -1 is returned gracefully. Option B is false because the function returns immediately upon finding the first occurrence due to the return statement inside the loop.
Step-by-step Derivation:
Trace the function logic:
- If
a = []andx = 5: Loop condition0 < 0is false, loop never executes, function returns-1. No abnormal termination. - If
a = [5, 5, 5]andx = 5: On first iteration (i=0),a[0] == 5is true, function immediately returns0 + 1 = 1. Function exits; subsequent occurrences are never checked. - If
a = [1, 2, 3]andx = 5: Loop completes all iterations without finding a match, function returns-1. This is the guaranteed behavior.
Conclusion: Only option C accurately describes the function's behavior.