JavaScript Program to Swap Two Variables

Updated on November 12, 2024
Swap two variables header image

Introduction

Swapping two variables in programming is a fundamental concept used in various applications, such as sorting algorithms and memory management. In JavaScript, swapping values between two variables can be accomplished in several efficient ways without the need for a temporary third variable.

In this article, you will learn how to swap two variables using different methods in JavaScript. Each section provides a clear example of swapping techniques, paving the way for you to utilize these methods efficiently in your projects.

Using Destructuring Assignment

Swap Variables with Array Destructuring

  1. Initialize two variables with any desired values.

  2. Use array destructuring syntax to swap their values.

    javascript
    let a = 1, b = 2;
    [a, b] = [b, a];
    console.log(a, b);  // Outputs: 2 1
    

    This code snippet demonstrates array destructuring to swap the values of a and b. The swapping is concise and requires a single line of code.

Using Arithmetic Operations

Swap Using Addition and Subtraction

  1. Start with two numeric variables.

  2. Use addition and subtraction to swap their values without a third variable.

    javascript
    let x = 5, y = 10;
    x = x + y;
    y = x - y;
    x = x - y;
    console.log(x, y);  // Outputs: 10 5
    

    The above approach uses arithmetic to interchange the values. It's a clever trick but limited to numbers and may lead to overflow with very large numeric values.

Swap Using Multiplication and Division

  1. Consider another arithmetic-based swapping for numeric variables.

  2. Use multiplication and division for swapping.

    javascript
    let x = 3, y = 4;
    x = x * y;  // x becomes 12
    y = x / y;  // y becomes 3
    x = x / y;  // x becomes 4
    console.log(x, y);  // Outputs: 4 3
    

    Similar to addition and subtraction, this technique is restricted to numbers. It risks division by zero and overflow errors.

Using Bitwise XOR

Swap Using XOR Operator

  1. Initialize two integer variables.

  2. Apply XOR operations to swap their values without a third variable.

    javascript
    let p = 6, q = 9;
    p = p ^ q;
    q = p ^ q;
    p = p ^ q;
    console.log(p, q);  // Outputs: 9 6
    

    XOR is a bitwise operation that works for integers. It's extremely efficient and safe from arithmetic overflow.

Conclusion

Swapping variables in JavaScript can be achieved through multiple methods without necessarily requiring a temporary placeholder. Destructuring assignment is notably the most straightforward and modern approach, suitable for most use cases. However, arithmetic and bitwise techniques provide additional tools for specific scenarios, mainly involving number types. You have now mastered various strategies to swap values, which you can apply directly in appropriate situations to write cleaner and more efficient code.