0

I am creating a web-app and have something like this:

this.arr = [];

(async function f() {
    try {
        const response = await this.myService.getData();
        const data = response.data;
        data.forEach((entry) => {
            this.arr.push(new MyObject(entry.valueOne, entry.valueTwo));
        });
    } catch (error) {
        console.log(error);
    }
}).call(this);

Now when I query this.arr I get the following output:

[]
0: Object { valueOne: "foo", valueTwo: "bar" }
1: Object { valueOne: "foobar", valueTwo: "foo" }
length: 2
<prototype>: Array []

So try to log only the first element via

this.console.log(this.arr[0]);

and I get

TypeError: this.arr[0] is undefined

I think the problem is, that I push elements to an empty array, because when I create the array by hand like

console.log(
    [
        {name: "foo", description: "bar"},
        {name: "foobar", description: "foo"},
    ]
);

I get the following output:

(2) […]
0: Object { name: "foo", description: "bar"}
1: Object { name: "foobar", description: "foo"}
length: 2
<prototype>: Array []

Almost the same, except that the length of the hand-generated array is displayed in the brackets.

Andreas
  • 430
  • 5
  • 21
  • Can you add a running snippet please? – Jorge Fuentes González May 06 '19 at 08:17
  • can you please check and share what's contain in your **this.arr** ? – lochawala May 06 '19 at 08:18
  • 1
    `console.log(this.arr);` logs the array, which later gets updated with new data, and the console shows the data. `console.log(this.arr[0]);` logs the first value in the array, which is undefined at the time, and since it isn't a reference, when the array changes, the log doesn't. – Quentin May 06 '19 at 08:20
  • @JorgeFuentesGonzález I tried to, but it does not make that much sense, because most of the data is fetched async. Injecting more sample data would destroy the actual code, in my opinion. – Andreas May 06 '19 at 08:25
  • @PrAtikLochawala the second code snipped shows the content of ```this.arr``` – Andreas May 06 '19 at 08:26
  • @Andi Actually injecting data will not destoy the code. Is a really good practice as is some way of having unit tests. Tests where you can mock data and only run part of the code that you want to test. You don't need to run all the code to just test some part of it as long as you can mock part of the code. – Jorge Fuentes González May 06 '19 at 08:28
  • @Andi If you read this https://en.wikipedia.org/wiki/Test-driven_development you will get the idea. Is a must-read if you want to create good code. – Jorge Fuentes González May 06 '19 at 08:29
  • @Quentin that's it, thanks! – Andreas May 06 '19 at 08:45

0 Answers0