Arrays

Safe Array Indexing

Safe Array Indexing

Array indexing returns undefined when a position does not exist. That can be fine inside quick scripts, but application code often needs a clearer result when an index comes from a URL, form field, or saved setting.

A small helper can turn a raw index read into an explicit contract. The caller gets the array item for valid positions and a deliberate fallback for positions outside the list.

Your task: Complete itemAt so it returns the item at the requested index when that index is valid. Return null for negative indexes, indexes past the end, and empty arrays.

Free with a JS Exercises account

Sign in to start coding, run your solution, and keep your progress saved for later. No payment needed.

By continuing, you agree to our Terms and Privacy Policy. We'll send occasional product updates and news. You can unsubscribe anytime.

Safe Array Indexing

Array indexing returns undefined when a position does not exist. That can be fine inside quick scripts, but application code often needs a clearer result when an index comes from a URL, form field, or saved setting.

A small helper can turn a raw index read into an explicit contract. The caller gets the array item for valid positions and a deliberate fallback for positions outside the list.

Your task: Complete itemAt so it returns the item at the requested index when that index is valid. Return null for negative indexes, indexes past the end, and empty arrays.

Free with a JS Exercises account

Sign in to start coding, run your solution, and keep your progress saved for later. No payment needed.

By continuing, you agree to our Terms and Privacy Policy. We'll send occasional product updates and news. You can unsubscribe anytime.

Console

Run code to see output.