Skip to main content

Array destructuring


MDN Docs

//takes this code:

const dimensions = [20, 5]

// create variables
const width = dimensions[0];
const height = dimensions[1];

// log them
console.log(width); //20
console.log(height); //5

//And makes this code:
const dimensions = [20, 5]

// create variables
const [width, height] = dimensions; //one line instead of 2 lines :)

// log them
console.log(width); //20
console.log(height); //5

You can identify destructuring when you see the square brackets [] on the left side of the equal sign.

Quick Recap


  • Array destructuring is syntactic sugar (meaning that it makes your code easier to read).
  • The order in array destructuring matters, as every variable will be matched to the corresponding array item.
  • You can identify destructuring when you see the square brackets [] on the left side of the equal sign.

Lat and Longitude


const getLocationString = location => {
//destructure into 2 variables: lat & lng
const [lat, lng] = location // <-- destructuring

return `The latitude is ${lat} and the longitude is ${lng}`;
}

// Sample usage - do not modify
const location = [24.235235, 2.5734];
console.log(getLocationString(location)); // "The latitude is 24.235235 and the longitude is 2.5734"

Get Full Names


const getFullName = user => {
const [firstName, lastName] = user;
return `${firstName} ${lastName}`;
}

// Sample usage - do not modify
console.log(getFullName(["Solo", "Stroup"])); // "Solo Stroup"
console.log(getFullName(["Liz", "Funkhouser"])); // "Liz Funkhouser"

Array Concatenation


MDN Docs

const lat = [5.234];
const lng = [1.412];
const point = [...lat, ...lng];
console.log(point); // [5.234, 1.412];

//don't confuse that with this:
const lat = [5.234];
const lng = [1.412];
const point = [lat, lng];
console.log(point); // array[1], array[1];

//another example:
const items = ["Pizza", "Tacos"];

const otherItems = [...items, "Noodles"];
console.log(otherItems); // ["Pizza", "Tacos", "Noodles"]

Example:


/**
* @param {string[]} apps1
* @param {string[]} apps2
*/
const getApps = (apps1, apps2) => {
return [...apps1, ...apps2]

}

// Sample usage - do not modify
console.log(getApps(["Calculator", "Whatsapp"], ["Chrome", "Firefox"])); // ["Calculator", "Whatsapp", "Chrome", "Firefox"]

Recap


  • Array destructuring is syntactic sugar (meaning that it makes your code easier to read).
  • The order in array destructuring matters, as every variable will be matched to the corresponding array item.
  • You can identify destructuring when you see the square brackets [] on the left side of the equal sign.
  • You can concatenate/merge several arrays into a new array using the ... spread syntax.