Skip to content

Destructuring Assignment

Destructuring assignment is a feature in JavaScript to unpack values from arrays or objects into distinct variables.

Destructuring Arrays

js
const numbers = [1, 2, 3];
const [first, second, third] = numbers;

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

Destructuring Arrays can be useful in returning multiple values from a function:

js
function getCoordinates() {
	// calculate lat, lon;
	return [lat, lon];
}

const [latitude, longitude] = getCoordinates();

Destructuring Objects

js
const city = {
	name: 'San Francisco',
	population: 8000000,
};

const { name, population } = city;

console.log(name); // 'San Francisco'
console.log(population); // 8000000

Another useful feature is adding default values to the destructuring:

js
const city = {
	name: 'San Francisco',
	population: 8000000,
};

const { name, temperature = 60 } = city;

console.log(name); // 'San Francisco'
console.log(temperature); // 60

You can also rename the variable:

js
const { name: cityName } = city

console.log(cityName) // 'San Francisco'

In Practice:

Destructuring is extremely useful to keep the code clean. For example in react-query, the return value of useQuery is neatly named for us.

js
  const { isPending, error, data } = useQuery({
   // ...
  })

Sometimes renaming the variable here is super useful to avoid variable name conflicts:

js
const { data: populationData } = useQuery({
	//...
})

const { data: temperatureData } = useQuery({
	//...
})

console.log(populationData)
console.log(temperatureData)