freeCodeCamp/curriculum/challenges/english/02-javascript-algorithms-an.../es6/use-destructuring-assignmen...

1.9 KiB

id title challengeType forumTopicId
587d7b89367417b2b2512b4b Use Destructuring Assignment to Assign Variables from Arrays 1 301213

Description

ES6 makes destructuring arrays as easy as destructuring objects. One key difference between the spread operator and array destructuring is that the spread operator unpacks all contents of an array into a comma-separated list. Consequently, you cannot pick or choose which elements you want to assign to variables. Destructuring an array lets us do exactly that:
const [a, b] = [1, 2, 3, 4, 5, 6];
console.log(a, b); // 1, 2

The variable a is assigned the first value of the array, and b is assigned the second value of the array. We can also access the value at any index in an array with destructuring by using commas to reach the desired index:

const [a, b,,, c] = [1, 2, 3, 4, 5, 6];
console.log(a, b, c); // 1, 2, 5

Instructions

Use destructuring assignment to swap the values of a and b so that a receives the value stored in b, and b receives the value stored in a.

Tests

tests:
  - text: Value of <code>a</code> should be 6, after swapping.
    testString: assert(a === 6);
  - text: Value of <code>b</code> should be 8, after swapping.
    testString: assert(b === 8);
  - text: Should use array destructuring to swap a and b.
    testString: assert(/\[\s*(\w)\s*,\s*(\w)\s*\]\s*=\s*\[\s*\2\s*,\s*\1\s*\]/g.test(code));

Challenge Seed

let a = 8, b = 6;
// change code below this line

// change code above this line
console.log(a); // should be 6
console.log(b); // should be 8

Solution

let a = 8, b = 6;
[a, b] = [b, a];