It seems like you are using an ad blocker. To enhance your experience and support our website, please consider:

  1. Signing in to disable ads on our site.
  2. Sign up if you don't have an account yet.
  3. Or, disable your ad blocker by doing this:
    • Click on the ad blocker icon in your browser's toolbar.
    • Select "Pause on this site" or a similar option for lancecourse.com.

Javascript in 100 bits

Course by zooboole,

Last Updated on 2025-01-28 08:04:00

Lesson 76 – JavaScript Destructuring Assignment (Arrays & Objects)

Destructuring is a concise way to extract values from arrays or properties from objects into distinct variables. It makes code cleaner and more readable.


Destructuring Arrays

const numbers = [1, 2, 3];

// Traditional way
const first = numbers[0];
const second = numbers[1];

// Destructuring
const [a, b] = numbers;

console.log(a); // 1
console.log(b); // 2

You can also skip elements:

const [x, , z] = [10, 20, 30];
console.log(z); // 30

Use default values:

const [p = 100, q = 200] = [50];
console.log(p); // 50
console.log(q); // 200

Destructuring Objects

const person = {
  name: "Jane",
  age: 25,
  country: "Ghana"
};

const { name, age } = person;

console.log(name); // Jane
console.log(age);  // 25

Rename variables while destructuring:

const { name: fullName, age: years } = person;

console.log(fullName); // Jane
console.log(years);    // 25

Provide default values:

const { gender = "Not specified" } = person;
console.log(gender); // Not specified

Nested Destructuring

const user = {
  id: 1,
  profile: {
    username: "devahmed",
    email: "ahmed@example.com"
  }
};

const {
  profile: { username, email }
} = user;

console.log(username); // devahmed

Try Your Hand

  1. Destructure this array and get the first and last item:

    const colors = ["red", "green", "blue", "yellow"];
  2. Destructure the object and rename the keys:

    const settings = {
    resolution: "1080p",
    fullscreen: true
    };

Summary

  • Destructuring makes it easy to assign variables from arrays or objects.
  • Works great with function parameters and default values.
  • Helps reduce boilerplate code and improves readability.