0

I've been going through Wes Bos' Javascript30 course, and have been messing with JSON and arrays.

I'm trying to figure out what's happening here.

I have a simple JSON test file that I'm fetching and pushing into an array, and an identical array created locally. When I try to console.log the name of the first person with the local array, it works fine. But when I try to console.log the name of the first person in the JSON fetched array, I get an error "Uncaught TypeError: Cannot read property 'name' of undefined"

JSON file:

[
  {
    "name":"Sean",
    "Age":"23"
  },
  {
    "name":"kev",
    "Age":"23"
  }
]

javascript:

const people = [];
const peopleLocal = [ {"name":"Sean", "age":"23"}, {"name":"kev", 
"age":"23"}];
const endpoint = "test.json";
fetch(endpoint)
  .then(blob => blob.json())
  .then(data => people.push(...data));

console.log(people);
console.log(peopleLocal);


console.log(peopleLocal[0].name);
console.log(people[0].name);

console.log(people) and console.log(peopleLocal) returns the same array of objects. Then console.log(peopleLocal[0].name) returns "Sean". But console.log((people[0].name) returns the undefined error mentioned above. Why?

Fullstack Guy
  • 16,368
  • 3
  • 29
  • 44
itsseanl
  • 77
  • 1
  • 10

1 Answers1

1

They are not acting differently at all, you are just printing the name way before the asynchronous fetch finishes. Try printing it the right time, namely in the calback where you receive the response, like this:

const people = [];
const peopleLocal = [ {"name":"Sean", "age":"23"}, {"name":"kev", 
"age":"23"}];
const endpoint = "test.json";
fetch(endpoint)
  .then(blob => blob.json())
  .then(data => {
      people.push(...data);
      console.log(people);
      console.log(people[0].name);
  });

console.log(peopleLocal);
console.log(peopleLocal[0].name);

But how come console.log(people) works outside of the callback, but not console.log(people[0].name)?

Good question. The developer console's object browser actually stores the reference to the object, not a copy of it, so when you look at it on the console, you see the latest values, not the ones at the time of being printed.

See this SO answer:

console.log() shows the changed value of a variable before the value actually changes

Tamas Hegedus
  • 28,755
  • 12
  • 63
  • 97
  • Okay that works... I feel dumb. But how come console.log(people) works outside of the callback, but not console.log(people[0].name)? If it can read the entire array it only makes sense that it could read part of the first object in the array. – itsseanl Sep 02 '18 at 10:27