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

The following JavaScript function searches for a number among integers: Choose the correct...

Accenture technical mcq question, verified with a worked answer. Free to practise - no sign-up.

The following JavaScript function searches for a number among integers:

function find(x, a) {
  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: A. If x is not found in array a, the function returns -1

Option A is correct. The function iterates through the array and returns -1 if no match is found (line 6). Option B is incomplete (missing return value description). Option C is false: an empty array causes the loop condition i < a.length to be false immediately, so no abnormal termination occurs—the function simply returns -1. Therefore, D is also incorrect.

Step-by-step Derivation:
Trace execution:

  1. Element not found: Loop runs through all indices without matching; reaches line 6 and returns -1. ✓ A is correct.

  2. Multiple occurrences: Loop encounters first match at some index i, returns i + 1 immediately. Remaining occurrences are never checked. B is incomplete/misleading.

  3. Empty array (a = []):

    • a.length = 0
    • Loop condition: 0 < 0 is false
    • Loop never executes
    • Returns -1 normally (no crash)
    • C is false.
  4. Since A is correct, D is false.