1. Swap helper
This helper receives an array and two indexes to exchange.
function swapItems(arr, i, j)Typorithm · easy
Step 1 of 4 · intro card
Basic Patterns
The swap pattern exchanges two values without losing either value.
Sorting algorithms often need to move values by swapping two positions.
In JavaScript, destructuring makes a compact in-place swap possible.
The key idea is that both right-side values are read before the left-side assignments happen.
Use two indexes to choose positions.
Read both original values before assigning.
Destructuring avoids a temporary variable.
function swapItems(arr, i, j) {
[arr[i], arr[j]] = [arr[j], arr[i]];
return arr;
}Connect each part of the code to the concept before you type.
This helper receives an array and two indexes to exchange.
function swapItems(arr, i, j)The left and right array positions are reassigned in one step.
[arr[i], arr[j]] = [arr[j], arr[i]]Return the same array after changing it in place.
return arrRead the concept map and follow the code breakdown.
Type the implementation, repair mistakes and work through every recall exercise.
Use the final check without hints; revisit weak concepts in short practice sessions.