0

I ran into a rather weird problem when I try to code a specific part of my bot! To make it simple and short , I have an object array that contains various properties ( see code for examples). What i want to do is I want to get all the specific property in that array ( name for example ) and print that out in a console. I tried looping using a simple for loop , and every successful loop, i asked the console to log arrayname[i].name! See code for clarification!

module.exports = {
  commands: ["test"],
  callback: (message, arguments, text) => {
    const data = [
      { name: "Ren", id: "NURE1" },
      { name: "Isa", id: "SCIS1" }
    ]

    for (var i = 0; i <= data.length; i++) {
      console.log(data[i].name)
    }
  }
}

the problem is it does log the code as expected - Ren and Isa in this case for example but as soon as the console log, the app crashes throwing the error - property name is undefined ;-; - the same goes when i used id. Is there something I am doing wrong??

Lioness100
  • 8,260
  • 6
  • 18
  • 49
Ren
  • 27
  • 5
  • 4
    `i <= data.length` should be `i < data.length`. Arrays are indexed starting with `0`. That means if there are three entries (`length` is `3`), the entries are at indexes `0`, `1`, and `2`. Or [loop through the array another way](https://stackoverflow.com/questions/9329446/for-each-over-an-array-in-javascript), for instance, `for-of`. – T.J. Crowder Apr 29 '21 at 15:09

1 Answers1

0

This is because data only has 2 items (index 0 and index 1), but you're trying to access 3 items (index 0, 1, and 2). Index 2 is undefined, so it's throwing an undefined error. You should use i < data.length instead of i <= data.length in your for loop.

You can also use a for ... of loop to avoid issues like this with indices:

for (let item of data) {
    console.log(item.name);
}
Nisala
  • 1,313
  • 1
  • 16
  • 30
  • 2
    This is fundamentally a typo-level question. Better just to comment if no one else has and vote to close as typo than to *answer*. If there are multiple answers, or on upvoted answer, it prevents the OP from deleting the question. (And if not typo-level, it's a duplicate of existing content, probably a couple of dozen of them.) – T.J. Crowder Apr 29 '21 at 15:11