Arrays

Replace Without Mutation

Replace Without Mutation

Replacing an array item by index is direct, but doing it on the input array changes data that other code may still be using. The safer pattern is to copy the array first and perform the replacement on the copy.

This is common when a single item in a list changes but the old list is still needed for comparison, rendering, or rollback.

Your task: Complete withReplacement so it returns a new array where the item at index has been replaced by value. If the index is outside the array, return a copy with the same contents.

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.

Replace Without Mutation

Replacing an array item by index is direct, but doing it on the input array changes data that other code may still be using. The safer pattern is to copy the array first and perform the replacement on the copy.

This is common when a single item in a list changes but the old list is still needed for comparison, rendering, or rollback.

Your task: Complete withReplacement so it returns a new array where the item at index has been replaced by value. If the index is outside the array, return a copy with the same contents.

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.