Practice
JavaScriptData StructuresReactConcepts
Sign in
← Back to problems

Default on Out-of-Range

Asynchronous JavaScriptmedium

Course · Section 16: Asynchronous JavaScript: Promises, Async/Await, and AJAX · Lecture 275: Error Handling With try...catch

Implement `tryOrDefault(arr, index, fallback)` that reads `arr[index]` from a helper which throws when the index is out of range, returning `fallback` if it throws.

Sample tests

Input: tryOrDefault([1,2,3], 1, 0)
Output: 2
Input: tryOrDefault([1], 5, -1)
Output: -1

+ 1 hidden test run on Submit.

Hints

Common pitfalls
  • Returning undefined for an out-of-range index instead of the fallback.

Learning resources

  • MDN: try...catch
Approach & explanation (try first)

Wrapping a throwing accessor in try/catch lets you supply a fallback on bad indices.

Loading...
⌘/Ctrl + Enter

Run your code to see results.