Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 29 additions & 1 deletion src/scripts/main.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,31 @@
'use strict';

// write your code here
const population = document.querySelectorAll('.population');
const averagePopulation = document.querySelector('.average-population');
const totalPopulation = document.querySelector('.total-population');
const newPopulation = [...document.querySelectorAll('.population')];

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This line queries the DOM for the same elements as on line 3. It's more efficient to query the DOM only once and reuse the resulting NodeList. The population variable from line 3 can be used directly in the for...of loop on line 9.

let totalPopulationResult = 0;

for (const onePopulation of newPopulation) {
totalPopulationResult += Number(onePopulation.innerText.split(',').join(''));
}

const newTotalPopulationResult = String(totalPopulationResult).split('');

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This logic for adding thousands separators is effective, but it's repeated again on lines 23-28. To avoid code duplication, consider creating a reusable function for this task. You could also look into the standard toLocaleString() method, which can format numbers like this in a single line.

const resultTotal = [];

while (newTotalPopulationResult.length) {
resultTotal.unshift(newTotalPopulationResult.splice(-3).join(''));
}

const averagePopulationResult = Math.round(
totalPopulationResult / population.length,
);
const newAveragePopulationResul = String(averagePopulationResult).split('');

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There's a small typo in this variable name. It should probably be newAveragePopulationResult to be consistent.

const resultAverage = [];

while (newAveragePopulationResul.length) {
resultAverage.unshift(newAveragePopulationResul.splice(-3).join(''));
}

totalPopulation.innerText = resultTotal.join(',');
averagePopulation.innerText = resultAverage.join(',');
Loading