Swapping Values Without a Temporary Variable | Javascript

 let a = 1, b = 2;

[a, b] = [b, a];

// Output: a = 2, b = 1 

AI Explanation

This code snippet demonstrates a technique called array destructuring in JavaScript. Initially, the variables `a` and `b` are assigned the values `1` and `2` respectively. The line `[a, b] = [b, a];` uses array destructuring to quickly swap the values of `a` and `b`. Here's how it works: 1. The right side `[b, a]` creates a new array with the values of `b` and `a` in reversed order. So, `[2, 1]`. 2. The left side `[a, b]` uses array destructuring to assign the values from the right side array `[2, 1]` to the variables on the left side. This effectively swaps the values of `a` and `b`. After this line of code is executed, the values of `a` and `b` are swapped. So, the output is `a = 2, b = 1`.