DEV Community

Moarij0
Moarij0

Posted on

Writing an Appliance Energy Calculator in JavaScript

Appliance energy calculators answer one simple question: how many units does this device use in a month? It is a great small project for learning about units and clean input handling.

The formula

One unit of electricity is one kilowatt-hour (kWh).

function monthlyUnits({ watts, hoursPerDay, days = 30, quantity = 1 }) {
  if (watts <= 0 || hoursPerDay < 0 || hoursPerDay > 24) {
    throw new Error('Check wattage and hours');
  }
  return +((watts * hoursPerDay * days * quantity) / 1000).toFixed(1);
}

// Example: two 75 W ceiling fans running 12 hours a day
console.log(monthlyUnits({ watts: 75, hoursPerDay: 12, quantity: 2 })); // 54
Enter fullscreen mode Exit fullscreen mode

Make it more realistic

  • Duty cycle: fridges and ACs do not draw full power all the time. Let users enter a percentage
  • Summing a list: let users add several appliances and show a total
  • Units to money: tariffs are usually slab-based, so pass the total units into a separate slab function rather than multiplying by one rate

See it in a real tool

BaKhabar Pakistan's appliance calculator shows units per appliance, and its solar calculator uses total usage to suggest a system size. Comparing your output with a working tool is a good way to check your maths.

Top comments (0)