swap array of lenght 2 in javascript

There are several ways to swap two elements in an array, but one common method is to use array destructuring. Here's an example:

index.tsx
let arr = ['item1', 'item2'];
[arr[0], arr[1]] = [arr[1], arr[0]];
console.log(arr);  // Output: ['item2', 'item1']
116 chars
4 lines

In the code above, we're using array destructuring to swap the elements at indices 0 and 1 in the arr array. The left-hand side of the assignment let [a, b] = ... defines two variables a and b that will hold the swapped values. The right-hand side of the assignment [b, a] is an array literal that holds the swapped values in reverse order.

By using array destructuring, we don't have to create a temporary variable to hold one of the values during the swap. Instead, we can assign the swapped values directly to the array elements using the destructuring syntax.

gistlibby LogSnag