1. Temporary Variable
- Create a temporary variable to store the value of the first variable
- Set the first element to the value of the second variable.
- Set the second variable to the value in the temporary variable.
let a = 1; let b = 4; // Swap variables let temp = a; a = b; b = temp; console.log(a); // 4 console.log(b); // 1
2. Array Destructuring Assignment
- Create a new array, containing both variables in a particular order.
With this method, we can create a concise one-liner to do the job.
let a = 1; let b = 4; [a, b] = [b, a]; console.log(a); // 4 console.log(b); // 1