Why Use Destructuring Instead Of Indexing For An Array in JavaScript

Using destructuring make your code more concise, readable, and expressive. Here are several reasons why you should prefer destructuring:

1. Clarity and readability

Destructuring allows you to assign array elements to variables with meaningful names, making your code easier to understand compared to using numeric indices.

Also, it reduces repetition by extracting multiple values from an array in a single line of code.

// Without destructuring
const array = [1, 2, 3];
const first = array[0];
const second = array[1];
const third = array[2];

// With destructuring
const [first, second, third] = array;

2. Easier to swap variables

Destructuring simplifies variable swapping without needing a temporary variable.

// Without destructuring
let a = 1;
let b = 2;
let temp = a;
a = b;
b = temp;

// With destructuring
let a = 1;
let b = 2;
[a, b] = [b, a];

3. Support for default values

Destructuring allows you to provide default values for variables in case the corresponding array elements are undefined.

const [first = "default", second = "default"] = [];
console.log(first); // 'default'
console.log(second); // 'default'

4. Selective extraction

You can choose to extract only certain elements from an array using destructuring.

const [first, , third] = [1, 2, 3, 4, 5];

5. Convenient when dealing with functions that return arrays

Instead of assigning each element of the returned array to separate variables, you can destructure the array directly into meaningful variable names in a single line, which improves code readability and conciseness.

// Function that returns an array
function getUser() {
  return ["John", "Doe", 30];
}

// Without destructuring
const userArray = getUser();
const firstName = userArray[0];
const lastName = userArray[1];
const age = userArray[2];

// With destructuring
const [firstName, lastName, age] = getUser();

Overall, using destructuring can lead to cleaner, more maintainable code in JavaScript, particularly when working with arrays and tuples.

Get my free, weekly JavaScript tutorials

Want to improve your JavaScript fluency?

Every week, I send a new full-length JavaScript article to thousands of developers. Learn about asynchronous programming, closures, and best practices — as well as general tips for software engineers.

Join today, and level up your JavaScript every Sunday!

Thank you, Taha, for your amazing newsletter. I’m really benefiting from the valuable insights and tips you share.

- Remi Egwuda