swap function javascript code example

Example 1: swap function javascript

let a = 1;
let b = 2;
let temp;

temp = a;a = b;b = temp;
a; // => 2
b; // => 1

Example 2: swap function javascript

let a = 1;
let b = 2;

a = a ^ b;b = a ^ b;a = a ^ b;
a; // => 2
b; // => 1

Example 3: swap function javascript

function swap(x, y) {
    var t = x;
    x = y;
    y = t;
    return [x, y];
}

console.log(swap(2, 3));

Example 4: swap function javascript

let a = 1;
let b = 2;

a = a + b;b = a - b;a = a - b;
a; // => 2
b; // => 1

Example 5: swap function javascript

let a = 1;
let b = 2;

[a, b] = [b, a];
a; // => 2
b; // => 1

Example 6: swap function javascript

function swap(x, y) {
    return [y, x];
}

console.log(swap(2, 3));