If you don’t use destructuring assignment, swapping two values requires a temporary variable. Whereas using a destructuring feature, two variable values can be swapped in one destructuring expression. Let’s swap two number variables in array destructuring assignment,
1 2 3 4 5 | var x = 10, y = 20; [x, y] = [y, x]; console.log(x); // 20 console.log(y); // 10 |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.