Home > Software design >  destructing array containing objects
destructing array containing objects

Time:11-28

let chosen = 4;

let team = [
  { titel: "ahmad", age: 20, available: true, skills: ["html", "css"] },
  { titel: "mizo", age: 30, available: false, skills: ["js", "react"] },
  { titel: "jo", age: 40, available: true, skills: ["pyhton", "django"] },
];

(() => {
  if (chosen === chosen) {
    let {
      titel,
      age,
      available,
      skills: [s1, s2],
    } = team[chosen - 1];
    console.log(`Team-${chosen}:
    name: ${titel}
    age:  ${age}
    skill: ${s1}
    availability: ${(() => {
      if (available) return `available`;
      else return `unavailable`;
    })()}
    `);
  } else return;
})();


why the given code above throws this error (Uncaught TypeError: Cannot destructure property 'titel' of 'team[(chosen - 1)]' as it is undefined.) in the console if you choose a number less than 1 or greater than 4 ??

CodePudding user response:

This is because it exceed the number of elements in the array.

the team array has 3 items.

To access the first item, whose index is 0, you would do team[0].

To access the last item, whose index is 2, you would do team [2]

When you do team[4-1], you end up with team[3] which has exceeded the length of the array, and is therefore undefined.

Remember, arrays in javascript are 0-indexed. That means the first item is always at index 0, and the last item is at team.length-1, which in this case, is 2.

  • Related