DEV Community

Shehzad Hussain
Shehzad Hussain

Posted on • Updated on

Write clean code in JavaScript with this! πŸ‘‡

Array destructuring. Here are 2 ways to do it:

const array = ["one", "two", "three"];
const [oneConst, twoConst, threeConst] = array;
oneConst = "one"
twoConst = "two"
threeConst = "three"

This way is the most commonly used.

I prefer it because it's more readable.

Here's the second way, which is not as widely used or known:

const array = ["one", "two", "three"];
const { 0: oneConst, 1: twoConst, 2: threeConst } = array;
oneConst = "one"
twoConst = "two"
threeConst = "three"

By using array destructuring, you will improve the readability and simplicity of your code.

You will have a reduced error-prone code because you don't need to manage indices everywhere, making indexing mistakes less likely.

Hope that's helpful.

Top comments (2)

Collapse
 
starswan profile image
Stephen Dicks

why would anyone write code like this? Relying on an array containing exactly 3 entries (with undefined if fewer, and lost data if more) looks slightly strange to me as a practice.

Collapse
 
shehzadhussain profile image
Shehzad Hussain

You're right that this approach assumes the array has exactly three elements, which can lead to undefined values if it has fewer and ignored values if it has more.
To mitigate this, it’s good practice to include checks or default values
const [oneConst = "defaultOne", twoConst = "defaultTwo", threeConst = "defaultThree"] = array;
This way, you handle cases where the array might have fewer than three elements.