Thu Feb 02 2023

Swap Variable Value

JavaScript1127 views

File Name: swap-value-in-javascript.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Swap Variable</title>
    <script>
        function swap() {
            let num1 = document.getElementById('num1').value;
            let num2 = document.getElementById('num2').value;

            //using temporary variable
            // let temp = num1;
            // num1 = num2;
            // num2 = temp;

            //using destructuring assignment
            [num2, num1] = [num1, num2];

            document.getElementById('prev1').innerHTML = num1;
            document.getElementById('prev2').innerHTML = num2;
        }
    </script>
</head>
<body>
    <h1>Swap Value</h1>
    <input type="text" placeholder="Number 1" id="num1" />
    <input type="text" placeholder="Number 2" id="num2" />
    <button type="button" onclick="swap()">Swap</button>
    <h4>Number 1: <span id="prev1"></span></h4>
    <h4>Number 2: <span id="prev2"></span></h4>
</body>
</html>

Result Screenshot(s)

Swap Variable ValueWorking Sample0

We use cookies to improve your experience on our site and to show you personalised advertising. Please read our cookie policy and privacy policy.