0

This code is an external file, test.js, which is linked to from index.html, after the jQuery file. When I refresh my browser and go into the console, I get this error message:

Uncaught TypeError: Cannot read property 'starshipName' of undefined

on line 20, where I try to alert the starshipName property of the first item in the array.

var starships = [];

function starship(starshipName, model, manufacturer) {
  this.starshipName = starshipName;
  this.model = model;
  this.manufacturer = manufacturer;
}

function starshipData(data) {
  for (i = 0; i < data.results.length; i++) {
    var results = data.results[i];
    starships.push(new starship(results["name"], results["model"], results["manufacturer"]));
  }
}

$.getJSON('https://swapi.co/api/starships/', function(data) {
  starshipData(data);
});

alert(starships[0].starshipName);

However, when I type out the last line of code or log the starships array to the console, it works perfectly. I am very confused as to why this is happening and will appreciate any help! Thank you in advance.

Euan Williams
  • 22
  • 1
  • 2

1 Answers1

2

$.getJSON is an asynchronous function. This means that your alert() is called before starships is filled with data - hence the undefined property error.

All operations that depend on an async function must be placed in, or called from, the callback. Try this:

$.getJSON('https://swapi.co/api/starships/', function(data) {
  starshipData(data);

  // 1: place the call in the callback
  // 2: always use console.log to debug as it does not coerce data types
  console.log(starships[0].starshipName);
});
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339