let a = 1, b = 2; [a, b] = [b, a]; // Output: a = 2, b = 1
This one-liner uses array destructuring to swap the values of a
and b
without needing a temporary variable. It's a neat trick that makes your code cleaner and more concise. The [a, b] = [b, a]
syntax swaps their values by destructuring the array on the right-hand side and assigning it to the left-hand side.
const {name, age} = {name: 'John', age: 30}; // Output: name = 'John', age = 30
Here, object destructuring is used to extract name
and age
properties from an object directly into variables. This approach simplifies accessing object properties and enhances code readability.