Trying to add values from multiple object properties

Here’s what I have so far:

class MyTown {
    constructor (name, buildYear) {
        this.name = name;
        this.buildYear = buildYear;
    }
    
}

class Street extends MyTown {
    constructor (name, buildYear, strlength, size) {
        super (name, buildYear);
        this.strlength = strlength;
        this.size = size;
    }
}

const oceanAve = new Street ('Ocean Avenue', 1999, 20, 'big');
const evergreenSt = new Street ('Evergreen Street', 2008, 2, 'small');
const fourthSt = new Street ('4th Street', 2015, 10, 'normal');
const sunsetBlvd = new Street ('Sunset Boulevard', 1982, 35, 'huge');

const streetNames = [oceanAve, evergreenSt, fourthSt, sunsetBlvd];

const calcStreet = function () {
    let streetTotal = 0;
    for(const cur of streetNames) {
        streetTotal += cur.strlength;
        console.log(streetTotal);
    }
}

calcStreet();

I want to add all of the street lengths into one value (strlength). The way I currently have it set up, it gives me a value for each step of the calculation, thus logging to the console 4 different values… Is there a way for me to utilize only the final value?

Hi,

You can move the console.log() out of the loop to only get the last value.

  for (const cur of streetNames) {
    streetTotal += cur.strlength;
  }
  console.log(streetTotal);

https://jsfiddle.net/3yspov72/

2 Likes

Yup was about to say, move the console log outside of the for loop, it’s console logging multiple times because it’s getting iterated and called multiple times.

2 Likes

Excellent. Thank you so much!

1 Like