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.
Explanation:
- The value of
varA
is stored intempVar
. - The value of
varB
is assigned tovarA
(overwriting its original value, butvarA
‘s original value is safe intempVar
). - The value from
tempVar
(which wasvarA
‘s original value) is assigned tovarB
.
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).
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.
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.
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
andvarB
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.