Skip to content
Open
Changes from 1 commit
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
15 changes: 14 additions & 1 deletion src/scripts/main.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,16 @@
'use strict';

// write your code here
const populations = document.querySelectorAll('.population');

const numbers = Array.from(populations)
.map((span) => span.textContent.replace(/,/g, '').trim())
.map(Number);
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

You convert span text to Number here but do not validate the result. The task requires ensuring each string can be converted to a number; if conversion fails you'll get NaN. Consider filtering out non-numeric entries (e.g., check Number.isFinite) or handle invalid values explicitly before further processing.


const total = numbers.reduce((sum, num) => sum + num, 0);
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Reducing an array that may contain NaN values will produce NaN for the total. Make sure to filter the numbers array to include only valid numeric values (or handle NaN in the reducer) before calling reduce.

const average = numbers.length ? total / numbers.length : 0;
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Average is computed using numbers.length, which reflects the original list length and may include non-numeric entries. Use the length of the filtered/validated numeric array when dividing, and guard against division by zero.


document.querySelector('.total-population').textContent =
total.toLocaleString('en-US');
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

You format numbers with toLocaleString('en-US'), which yields comma thousands separators. This is fine if the populations are presented with that style; ensure the chosen locale matches the numeric style shown in the HTML (requirement: same numeric style as populations presented).


document.querySelector('.average-population').textContent =
Math.round(average).toLocaleString('en-US');
Loading