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, 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:

  1. If a = [] and x = 5: Loop condition 0 < 0 is false, loop never executes, function returns -1. No abnormal termination.
  2. If a = [5, 5, 5] and x = 5: On first iteration (i=0), a[0] == 5 is true, function immediately returns 0 + 1 = 1. Function exits; subsequent occurrences are never checked.
  3. If a = [1, 2, 3] and x = 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.