Bar Chart Data Visualization
What you'll build
A page that takes an array of data (e.g., monthly sales) and renders a bar chart using div elements. Each bar's height represents the data value, with labels below.
Goals
- Render data as visual bars using DOM elements
- Calculate bar heights relative to the maximum value
- Add labels and values to each bar
- Dynamically create and style elements from JavaScript
Prerequisites
- Arrays and array methods (map, max)
- DOM creation (createElement, appendChild)
- CSS styling via the style object
Steps
- 1
Define the data and HTML container
Create an array of data objects with label and value properties. Add a container div for the chart.
Code<div id="chart" style="display:flex;align-items:flex-end;gap:10px;height:300px;"></div> <script> const data = [ { label: "Jan", value: 45 }, { label: "Feb", value: 78 }, { label: "Mar", value: 32 }, { label: "Apr", value: 91 }, { label: "May", value: 60 }, ]; </script>Expected result
An empty chart container appears.
- 2
Calculate scale and render bars
Find the max value, then for each data point create a bar div whose height is proportional to the value. Add a label below each bar.
Codeconst chart = document.getElementById("chart"); const maxVal = Math.max(...data.map(d => d.value)); data.forEach(d => { const bar = document.createElement("div"); const heightPx = (d.value / maxVal) * 280; // 280px max height bar.style.cssText = `width:60px;height:${heightPx}px;background:#3b82f6;display:flex;align-items:flex-end;justify-content:center;color:white;`; bar.textContent = d.value; const col = document.createElement("div"); col.style.cssText = "display:flex;flex-direction:column;align-items:center;"; col.appendChild(bar); const label = document.createElement("span"); label.textContent = d.label; col.appendChild(label); chart.appendChild(col); });Expected result
A bar chart appears with 5 bars of varying heights and labels.
Hint
Each bar's height is (value / max) * maxBarHeight, scaling the largest bar to the container height.
- 3
Add input validation & error handling
Add validation at user input points: check for empty values, non-numbers, negatives, and other anomalies, using try/catch or conditionals to show friendly messages. Robust JS programs don't crash on unexpected input.
Codefunction safeParse(value) { if (value === null || value === undefined || value === "") { throw new Error("Input is empty"); } const num = Number(value); if (Number.isNaN(num)) { throw new Error(`"${value}" is not a valid number`); } return num; } try { const n = safeParse(userInput); process(n); } catch (err) { console.error(err.message); }Expected result
Empty or non-number input shows an error message instead of crashing; valid numbers process normally.
- 4
Add event listeners & interaction
Bind event listeners (click, input, keydown, etc.) to page elements so the program responds to user actions. Interactivity is the core value of JavaScript in the front end.
Codeconst button = document.querySelector("#action-btn"); const input = document.querySelector("#user-input"); button.addEventListener("click", () => { const value = input.value.trim(); if (!value) return; runMainLogic(value); }); input.addEventListener("keydown", (e) => { if (e.key === "Enter") button.click(); });Expected result
Clicking the button or pressing Enter triggers the main logic; empty input is ignored.
- 5
Test & console verification
Use console.assert or simple assertions to verify the core function's output; run the tests in the browser console to confirm all cases pass. Manual verification is an effective way to quickly confirm correctness.
Code// Run in browser console console.assert(coreFunc(10) === expected1, "case 1"); console.assert(coreFunc(0) === expected2, "edge: zero"); console.assert(coreFunc(-5) === expected3, "negative input"); console.log("All assertions passed ✓");Expected result
The console prints 'All assertions passed ✓' with no assertion failures.
Try it yourself
<div id="chart" style="display:flex;align-items:flex-end;gap:10px;height:300px;"></div>
<script>
const data = [
/* TODO: add data points */
];
// TODO: render bars
</script><div id="chart" style="display:flex;align-items:flex-end;gap:10px;height:300px;"></div>
<script>
const data = [
{ label: "Jan", value: 45 },
{ label: "Feb", value: 78 },
{ label: "Mar", value: 32 },
{ label: "Apr", value: 91 },
{ label: "May", value: 60 },
];
const chart = document.getElementById("chart");
const maxVal = Math.max(...data.map(d => d.value));
data.forEach(d => {
const bar = document.createElement("div");
const heightPx = (d.value / maxVal) * 280;
bar.style.cssText = `width:60px;height:${heightPx}px;background:#3b82f6;display:flex;align-items:flex-end;justify-content:center;color:white;`;
bar.textContent = d.value;
const col = document.createElement("div");
col.style.cssText = "display:flex;flex-direction:column;align-items:center;";
col.appendChild(bar);
const label = document.createElement("span");
label.textContent = d.label;
col.appendChild(label);
chart.appendChild(col);
});
</script>What you learned
You rendered data visually by dynamically creating DOM elements, calculating proportional sizes, and applying CSS styles from JavaScript — the foundation of data visualization without external libraries.
Related Resources
Related Lessons
Related Practice
- Predict Array map Output
Practice array transformations.
Related Cheatsheets
- JavaScript Cheatsheet
Array and DOM reference.
Related Glossary
A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.