Home >Web Front-end >JS Tutorial >How to Swap Array Elements in JavaScript: Destructuring vs. Temporary Variables?
Often when working with arrays, the need arises to swap two elements within the array. A common approach to this is:
var a = list[x], b = list[y]; list[y] = a; list[x] = b;
While this method works, it involves creating two temporary variables. Is there a simpler way to achieve the same result?
Yes, you can swap two elements in an array using only one temporary variable:
var b = list[y]; list[y] = list[x]; list[x] = b;
For JavaScript versions ES6 and later, a more concise and elegant solution exists: destructuring assignment. It allows you to swap values in an array in a single line, as shown below:
[arr[0], arr[1]] = [arr[1], arr[0]];
This technique produces the expected swapped result without the need for any temporary variables. It's a powerful feature that simplifies array manipulation tasks.
The above is the detailed content of How to Swap Array Elements in JavaScript: Destructuring vs. Temporary Variables?. For more information, please follow other related articles on the PHP Chinese website!