Mini Project: The Converter Toolkit

Grade 6, page 10 of 11. A one-minute read.

Let's build a little toolkit of useful conversion functions, and then use a loop to print a handy conversion table.

converters.js
// ---- The toolkit ----
const celsiusToFahrenheit = (c) => (c * 9) / 5 + 32;
const kmToMiles = (km) => km * 0.621371;
const kgToPounds = (kg) => kg * 2.20462;

function round(value, decimals = 1) {
  const factor = 10 ** decimals;
  return Math.round(value * factor) / factor;
}

function describeTemperature(c) {
  if (c <= 0) return "freezing 🥶";
  if (c < 15) return "chilly 🧥";
  if (c < 25) return "pleasant 🙂";
  if (c < 32) return "warm ☀️";
  return "HOT 🔥";
}

// ---- Use the toolkit ----
console.log("Temperature table");
for (let c = 0; c <= 40; c += 10) {
  const f = round(celsiusToFahrenheit(c));
  console.log(`${c}°C = ${f}°F (${describeTemperature(c)})`);
}

console.log("");
console.log(`A 5 km run is ${round(kmToMiles(5), 2)} miles.`);
console.log(`A 50 kg bag of rice is ${round(kgToPounds(50))} lb.`);

It prints

Temperature table
0°C = 32°F (freezing 🥶)
10°C = 50°F (chilly 🧥)
20°C = 68°F (pleasant 🙂)
30°C = 86°F (warm ☀️)
40°C = 104°F (HOT 🔥)

A 5 km run is 3.11 miles.
A 50 kg bag of rice is 110.2 lb.

Notice a little trick in describeTemperature: when an if statement's body is a single return, some developers leave out the curly braces and put it all on one line. That's allowed, and it's tidy for guard clauses like these. But if your if body has more than one statement, always use curly braces.

Try it yourself

Add two more converters to the toolkit: milesToKm and fahrenheitToCelsius. Test them by converting your answers back. (Does converting 30°C to Fahrenheit and back give you 30 again?)

You've mastered functions! That's huge. Seriously, functions are the heart of programming, and from here on, you'll use them in absolutely everything.

In Grade 7, we'll learn how to store not just one value, but a whole list of values, with arrays. (And yes, we'll finally explain why programmers count from zero.)

Reading is step one

CurlyScript turns these notes into a game: short questions, an explanation after every answer, and a test at the end of each grade. Free, with nothing to sign up for.

Start learning