Destructuring. Swapping values between two variables in JS open

Destructuring. Swapping values between two variables in JS

Destructuring made it very easy to exchange values between two variables:

    let first = "1";
    let second = "2";
    [first, second] = [second, first];

    console.log(first);     // 2
    console.log(second);    // 1

Another example:

    let numbers = [9, 3, 5, 2, 1, 4, 8, 6];
    for (let i = 0; i < numbers.length; i++)
        for (let j = 0; j < numbers.length; j++)
            if (nums[i] < nums[j]) {
                [nums[j], nums[i]] = [nums[i], nums[j]];
            }

    console.log(nums);  // [1, 2, 3, 4, 5, 6, 8, 9]
0

More

Leave a Reply

Your email address will not be published. Required fields are marked *

How many?: 22 + 22

lil-code© | 2022 - 2024
Go Top
Authorization
*
*
Registration
*
*
*
*
Password generation