In javascript, we can refer fields of an array or object via [] or calling .something of an object.

Let’s say we have the following arrays & objects and we want to reference their respective fields:

const arr = ["this", "is", "old"];
	const obj = {
	  a: "this",
	  b: "old",
	  c: "is"
	};

	//1\. try to access array the old style using []
	console.log(arr[0]);//this

	//2\. try to access object property using []
	console.log(obj['a']);//this

	//3.try to access object property via . keyword
	console.log(obj.c); //is

That seems straightforward but isn’t it tedious having to use [] or the . keyword to reference array or object properties? Here is where destructuring comes in.

Destructuring in javascript offers a cleaner & easier way to extract a group of data from array and objects into simpler statements.

Let’s take at the following example:

	//indicing array to retrieve fields
	const arr = [["apple", "banana", "orange"], ["one", "two","three"]];
	console.log(arr[0][0]);//apple
	console.log(arr[1][0]); //one

	const [fruits, number] = arr;
	const [apple, banana] = fruits;
	const [one, two] = number;
	console.log(apple); //apple
	console.log(one); //one

Over here, we have a double array. We index twice to get the information we need. On the example below, we used destructuring to differentiate between fruits and numbers from the array.

Afterward, we can further extract specific fruits(apple, banana) from the fruits array as well as extracting numbers from the number array.

This is so much cleaner comparing to indicing twice to get certain values from the double array. We can clearly differentiate between apples and numbers in the double array and it is easy for other people to follow the code.

const arr = ["Names", "Mary", "Diana", "Henry"];

	[header, ...names] = arr; 
	console.log(header);//Names
	console.log(names); //["Mary", "Diana", "Henry"]

	const emptyArr= [];
	[defaultVal = "New Name"] = arr;
	console.log(defaultVal);

This makes accessing a long array of data much easier instead of using a loop to access all the elements.

Aside from that, you can also default fields to values you are trying to extract out of the array. If the array is empty, as it is over here, it will set defaultVal to “New Name”.

#arrays #es6 #javascript #objects #web-development #programming

Array & Object Destructuring in JavaScript
1.40 GEEK