Introduction to JavaScript Array and Object Destructuring

·

3 min read

Hello, this is my first article on Hashnode! I saw a request for an article about JavaScript array and object destructuring so here is my take on it.

First of all, I find that the MDN documentation is a good place to start. A search led me to their article on destructuring assignment.

Array Destructuring

Here is an array of my favorite animals.

const myFavoriteAnimals = [
  "bird",
  "cow",
  "dog",
  "whale",
  "horse",
  "cat",
  "pig",
];

Say we want to assign my top three to their own variables. We could do it like this.

const favorite = myFavoriteAnimals[0];
const secondFavorite = myFavoriteAnimals[1];
const thirdFavorite = myFavoriteAnimals[2];

However, if we use array destructuring, it looks a little cleaner.

const [favorite, secondFavorite, thirdFavorite] = myFavoriteAnimals;

Object Destructuring

Here is an object with different words to refer to birds.

const birdWords = {
  scientific: "aves",
  young: "chick",
  female: "hen",
  male: "cock",
  collective: "flock",
  name: "bird",
};

Say we want to assign the scientific name and the collective name to their own variables. We could do it like this.

const scientific = birdWords.scientific;
const collective = birdWords.collective;

A cleaner way is to use object destructuring.

const { scientific, collective } = birdWords;

But what if we don't want our variables to have the same names as the object properties? If we want our variables to be called birdScientificTerm and birdCollectiveNoun we can do it like this.

const birdScientificTerm = birdWords.scientific;
const birdCollectiveNoun = birdWords.collective;

Or we could use object destructuring and do it like this.

const {
  scientific: birdScientificTerm,
  collective: birdCollectiveNoun,
} = birdWords;

Further Reading

These are just the most basic examples. You can learn more from this MDN article or this freeCodeCamp article.