Swap Variables in One Line of Code
Swap variables in one line of code. This one line will exchange the contents of two variables.
Previously exchanging variables would be done like this:
a = "car";
b = "van";
temp = a;
b = a;
a = temp;
Method 1:
// This one line of code swaps or exchanges the values of two variables
[a, b] = [b, a];
Example 1:
a = "car";
b = "van";
"I drive a " + a; // Returns: "I drive a car"
"She drives a " b; // Returns: "She drives a van"
[a, b] = [b, a];
"I drive a " + a; // Now returns: "I drive a van"
"She drives a " b; // Now returns: "She drives a car"