V.M
V.M

Reputation: 103

Why are there undefineds in my output?

Consider the following code:

function displayParkReport() {
  let title, part1, part2, part3;

  title = '---PARKS REPORT---\n';
  part1 = `Our ${data.all.parks.length} parks have an average of ${calcAverageParkAge()} years.`;

  data.all.parks.forEach(function(cur) {
    part2 += `${cur.name} has a tree density of ${cur.calcParkDensity()} trees per square km. \n`;
  });

  data.all.parks.forEach(function(cur) {
    if(cur.numberOfTrees > 1000) {
      part3 += `${cur.name} has more than 1000 trees. \n`;
    }
  });

  console.log(title + part1 + part2 + part3);
}

function displayStreetReport() {
  let title, part1, part2;

  title = '---STREETS REPORT---\n';
  part1 = `Our ${data.all.streets.length} streets have a total length of ${calcTotalStreetLength()} km, with an average of ${calcAverageStreetLength()} km. \n`;

  data.all.streets.forEach(function(cur) {
    part2 += `${cur.name}, built in ${cur.builtYear}, is a ${cur.size} street.\n`;
  });

  console.log(title + part1 + part2);
}

Here is the output:

---PARKS REPORT---
Our 5 parks have an average of 43.600 years.undefinedNorth Park has a 
tree density of 62.500 trees per square km. 
Central Park has a tree density of 102.174 trees per square km. 
West Park has a tree density of 70.833 trees per square km. 
East Park has a tree density of 100.000 trees per square km. 
Hasan Efendi has a tree density of 235.714 trees per square km. 
undefinedCentral Park has more than 1000 trees. 
East Park has more than 1000 trees. 
Hasan Efendi has more than 1000 trees. 

---STREETS REPORT---
Our 4 streets have a total length of 122 km, with an average of 30.5 km. 
undefinedBroadway, built in 2012, is a huge street.
Cavanough, built in 1992, is a normal street.
CrazyJoe, built in 2001, is a tiny street.
WestPark, built in 1956, is a small street.

Why is there random undefineds in the output?

Upvotes: 1

Views: 45

Answers (1)

Andrew Li
Andrew Li

Reputation: 57964

That's because you're using a += b, which is the same as a = a + b. Since part2 and part3 are undefined when you first access them, you're trying to do part2 = undefined + '...' which would lead the to undefined in there. Assign them initial values:

let part2 = '';
let part3 = '';

That way they aren't undefined when you first access them -- they'll be empty strings.

Upvotes: 3

Related Questions