Swap Two Numbers (JavaScript)

Swap Two Numbers

Swapping the values of two variables is a classic programming puzzle that demonstrates how to manipulate data in memory. The goal is to exchange the contents of two variables, so variableA gets the value of variableB, and variableB gets the value of variableA.

Understanding the Concept

Suppose you have a = 5 and b = 10. After swapping, a should be 10 and b should be 5.

Common Approaches

1. Using a Temporary Variable (Traditional Method):

This is the most straightforward and generally recommended method. It involves introducing a third variable to temporarily hold one of the values.

Copy to Clipboard

Explanation:

  • The value of varA is stored in tempVar.
  • The value of varB is assigned to varA (overwriting its original value, but varA‘s original value is safe in tempVar).
  • The value from tempVar (which was varA‘s original value) is assigned to varB.
2. Using Arithmetic Operations (Without Temporary Variable):

This method relies on addition and subtraction. While clever, it can be less readable and might have limitations (e.g., potential for overflow with extremely large numbers, though rare in modern JavaScript, or not working for non-numeric types).

Copy to Clipboard
3. Using XOR Operator (Bitwise):

This method works by exploiting the properties of the XOR bitwise operator (^). It’s concise and works for integer values.

Copy to Clipboard
4. JavaScript ES6 Destructuring Assignment (The Modern Way):

JavaScript provides a very elegant and concise way to swap variables using array destructuring, which implicitly handles the temporary storage.

Copy to Clipboard

Explanation:

  • The right side [varB, varA] creates a temporary array [value_of_varB, value_of_varA].
  • The left side then unpacks this array into varA and varB simultaneously. This is the most idiomatic way to swap variables in modern JavaScript.

Key Takeaways

  • Temporary Variable: The most robust and readable method for general swapping, especially if you’re not using modern JavaScript features.
  • In-place Swapping: Arithmetic and XOR methods achieve swapping without an explicit temporary variable, but have specific use cases and limitations.
  • Destructuring Assignment (ES6+): The preferred and most elegant way to swap variables in JavaScript due to its conciseness and readability.
  • Readability vs. Cleverness: Always prioritize clear and understandable code unless specific performance or memory constraints absolutely dictate otherwise.