OA. free
Free
Accenture Core Computer Science Core Computer Science Medium

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.

Choose one option.
Show answer & explanation
Answer: C. If x is not found in array a, the function returns -1.

The function iterates through the array and returns the 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 simply causes the loop condition to fail immediately, returning -1 gracefully. Option B is false because the function returns immediately upon finding the first occurrence, not all occurrences.

Step-by-step Derivation:
Trace through each scenario:

  1. Empty array (a.length = 0): The for loop condition (i < 0) is false on first iteration, so execution skips the loop and returns -1. No abnormal termination occurs.

  2. Multiple occurrences: When a[i] == x on the first match, the function executes 'return i + 1' immediately, exiting the function. Subsequent occurrences are never checked.

  3. x not found: The loop completes all iterations without matching any a[i] == x, then reaches the final 'return -1' statement, which executes successfully.

Therefore, only statement C is correct.