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

  1. If a.length === 0, the for loop condition i < a.length is false from the start, so the loop body never executes.
  2. The function then reaches return -1; and exits normally (no error).
  3. If x exists in the array at index i, the function returns i + 1 and exits immediately.
  4. If x is never found after checking all elements, the loop ends and return -1; executes.
  5. Therefore: A is false (no abnormal termination), B is false (only first occurrence returned), C is true (returns -1 when not found).