DEV Community

Arhan Khan
Arhan Khan

Posted on

Build a Unit Converter App with JavaScript

A unit converter turns one measurement into another — kilometres to miles, kilograms to pounds, Celsius to Fahrenheit. It is a small app, but it teaches you a pattern you will use everywhere: one value in, one value out, with a clean mapping between units.

How does it work? You pick a category, type a number, choose the from and to units, and multiply by a conversion factor. Length and weight use simple factors; temperature needs a formula because its scales start at different points.

<h2>Unit Converter</h2>
<select id="category">
  <option value="length">Length</option>
  <option value="weight">Weight</option>
  <option value="temperature">Temperature</option>
</select>
<input type="number" id="value" value="10">
<select id="from"></select>
<select id="to"></select>
<button id="convert">Convert</button>
<p id="result"></p>
Enter fullscreen mode Exit fullscreen mode
const factors = {
  length: { m: 1, km: 1000, mile: 1609.34, ft: 0.3048 },
  weight: { kg: 1, g: 0.001, lb: 0.453592, oz: 0.0283495 },
};

function convert(category, value, from, to) {
  if (category === 'temperature') {
    let celsius = from === 'C' ? value : from === 'F' ? (value - 32) * 5 / 9 : value - 273.15;
    return to === 'C' ? celsius : to === 'F' ? celsius * 9 / 5 + 32 : celsius + 273.15;
  }
  const inBase = value * factors[category][from];
  return inBase / factors[category][to];
}

document.getElementById('convert').addEventListener('click', () => {
  const category = document.getElementById('category').value;
  const value = Number(document.getElementById('value').value);
  const from = document.getElementById('from').value;
  const to = document.getElementById('to').value;
  const out = convert(category, value, from, to);
  document.getElementById('result').textContent = `${value} ${from} = ${out.toFixed(2)} ${to}`;
});
Enter fullscreen mode Exit fullscreen mode

This app is great for beginners because it teaches you data-driven code. Instead of writing an if for every pair of units, you store the factors in an object and let one function handle every combination. Adding a new unit later is one line, not a rewrite.

When should you build it? Whenever you want a project with real utility — cooking, travel, or study all need conversions. You can extend it later with currency (using a free exchange-rate API), or with a swap button that flips the from and to units.

The limits are worth knowing. Conversion factors are fixed, so a currency converter needs live rates from an API, not a hardcoded table. And always round the result for display — nobody wants to see 16.093440000000002 kilometres.

Start today: build the converter above, convert 10 kilometres to miles, then add one new unit of your own — like inches — and see how little code it takes.

Top comments (0)