-1
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 ??

  • 2
    I really don't understand what you're trying to do here. But since `chosen` is 4, `team[chosen - 1]` is `team[3]` which is `undefined` - your array has only 3 elements. And you can't use object destructuring on `undefined` [Also, unrelated, but why check `if (chosen === chosen)` when that will always be true?] – Robin Zigmond Nov 26 '21 at 23:59

1 Answers1

1

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.

Arky Asmal
  • 1,162
  • 4
  • 10