Nika Bo
Nika Bo

Reputation: 63

ForEach function returns undefined along with expected output

I am working on a javascript exercise in which we are supposed to use elements of ES6 such as classes, arrow functions and so on. This particular code is supposed to output park name along with tree density data for each park.

I could just hardcode each object individually into the console, but I would like to make my solution as scalable and close to the real world application as possible. However, I can't get the treeDensityReport function to work properly.

class Element {
  constructor(name, yearBuilt) {
    this.name = name;
    this.yearBuilt = yearBuilt;
  }
}

class Park extends Element {
  constructor(name, yearBuilt, trees, area) {
    super(name, yearBuilt);
    this.trees = trees;
    this.area = area;

    this.treeDensity = (() => this.trees / this.area)();

    this.parkAge = () => new Date().getFullYear() - this.yearBuilt;
  }
}

const parks = [];
let parkAges = [];

parks.push(park1 = new Park('Washington park', 1999, 1440, 300));
parks.push(park2 = new Park('Lincoln  park', 1984, 2550, 1000));
parks.push(park3 = new Park('Jefferson park', 2000, 2000, 455));

parkAges = parks.map(park => park.parkAge());

let averageParkAge = (parkAges.reduce((total, age) => total + age)) / parkAges.length;

function treeDensityReport(arr) {
  let string1;
  arr.forEach(function(element) {
    let string = `${element.name} has a tree density of ${element.treeDensity} \n`;
    string1 += string;
  });
  
  return string1;
}

console.log(`------PARKS REPORT------\n
Our ${parks.length} parks have an average age of ${averageParkAge} years.\n${treeDensityReport(parks)}
`)

I see the names and densities in console as expected but the function also returns undefined for some reason. Here is console output:

undefinedWashington park has a tree density of 4.8

Lincoln park has a tree density of 2.55

Jefferson park has a tree density of 4.395604395604396

Where is this undefined coming from? What am i missing?

Upvotes: 1

Views: 66

Answers (2)

Hameda169
Hameda169

Reputation: 633

in the first line of treeDensityReport, you must assign an empty string to string1. when you declare a variable, it's undefined default

Upvotes: 0

Matti Price
Matti Price

Reputation: 3551

let string1 defines string1 as undefined. Javascript does fun things when concatenating strings and ends up adding in the string literally as 'undefined'.

Try this instead

let string1 = ''

Upvotes: 2

Related Questions