Start learning free

LESSON 260 OF 671 · DESTRUCTURING, SORTING & BUILT-INS

Destructuring in JavaScript

Lesson

TL ; DR:

A small array can keep a pair of values together, like a movie's title and year. Destructuring unpacks it into variables in one line.


const movie = ["Frozen", 2013];    // a title and a year

console.log(movie[0]);             // Frozen

const [title, year] = movie;       // destructuring

console.log(title + " " + year);   // Frozen 2013

function firstAndLast(word) {
    return [word[0], word[word.length - 1]];
}

const [first, last] = firstAndLast("code");

console.log(first + last);         // ce


Full lesson:

Some values belong together. A movie has a title and a year. A point has an x and a y. JavaScript keeps a pair like that in a small array.

  • const movie = ["Frozen", 2013] makes the pair.
  • movie[0] is the first value, "Frozen". movie[1] is the second, 2013.

Destructuring gives each value its own name. Write the names in square brackets, in the same order as the values. After const [title, year] = movie;, title holds "Frozen" and year holds 2013.

A function can return two values in an array, with return [a, b]. The caller destructures the result, as in const [x, y] = f().

Watch the count. A name with no value to match gets undefined. In const [a, b, c] = movie;, c is undefined.


Your task

Rex the dog went for a long walk. pet holds his name and his age.

First, make splitTime return an array of two values: the whole hours and the minutes left.

Then destructure pet into name and age.

Last, call splitTime(135). Destructure its result into hours and mins.

The code already prints the three lines.

Expected output:

Rex
Rex is 4
Rex walked 2 h 15 min
STEP 1 OF 3
    Ctrl + Enter to check