US Sales Tax by State: Building a Lookup in JavaScript
US Sales Tax by State: Building a Lookup in JavaScript Sales tax in the United States is one of those problems that looks trivial until you actually build it. There is no single national rate. Each state sets its own b
US Sales Tax by State: Building a Lookup in JavaScript
Sales tax in the United States is one of those problems that looks trivial until you actually build it. There is no single national rate. Each state sets its own base rate, counties and cities pile on local rates, and five states charge nothing at all. If you are building a checkout page, an invoicing tool, or a price calculator, you need a lookup that is fast, maintainable, and honest about its limits.
In this article, we will build a small JavaScript sales-tax engine: a state-rate lookup, a total calculator, and a few edge cases that trip up real projects. If you would rather skip the code and just get a number, try the free US Sales Tax Calculator β it does the lookup for you.
Why a Simple Percentage Is Never Enough
A naive implementation hard-codes a single rate:
const TAX_RATE = 0.08;
const total = price * (1 + TAX_RATE);
That works for a demo and fails everywhere else. The real picture:
- State base rates range from 0% (Oregon, Montana, New Hampshire, Delaware, Alaska) to 7.25% in California.
- Local rates stack on top. The combined rate in some parts of Tennessee or Louisiana can exceed 11%.
- Some items are exempt. Groceries are untaxed in most states, clothing is exempt in Pennsylvania and Minnesota, and many states run annual tax-free weekends.
- Rates change. States and counties adjust rates every year, so a hard-coded table rots quickly.
A good engine separates the data (rates) from the logic (calculation), so updating a rate never means touching the math.
Step 1: The Rate Table
Start with a data structure keyed by state code. Keep the base state rate, the average local rate, and a flag for the no-tax states:
const STATE_RATES = {
CA: { name: "California", state: 0.0725, localAvg: 0.0143 },
NY: { name: "New York", state: 0.04, localAvg: 0.0449 },
TX: { name: "Texas", state: 0.0625, localAvg: 0.0194 },
FL: { name: "Florida", state: 0.06, localAvg: 0.0112 },
TN: { name: "Tennessee", state: 0.07, localAvg: 0.0277 },
OR: { name: "Oregon", state: 0, localAvg: 0, noTax: true },
DE: { name: "Delaware", state: 0, localAvg: 0, noTax: true },
MT: { name: "Montana", state: 0, localAvg: 0, noTax: true },
NH: { name: "New Hampshire", state: 0, localAvg: 0, noTax: true },
AK: { name: "Alaska", state: 0, localAvg: 0.0176 }, // no state tax, some local tax
};
Averaging local rates is a deliberate trade-off. A production checkout should resolve the exact county or ZIP code, but for a calculator, a quote tool, or an estimate, the state average is accurate enough β and you should label it as an estimate.
Step 2: The Calculator
With the data in place, the calculation itself is short:
function calculateSalesTax(subtotal, stateCode, options = {}) {
const state = STATE_RATES[stateCode.toUpperCase()];
if (!state) throw new Error(`Unknown state code: ${stateCode}`);
const { exempt = false, useLocalAvg = true } = options;
if (exempt || state.noTax) {
return { tax: 0, total: subtotal, rate: 0 };
}
const rate = state.state + (useLocalAvg ? state.localAvg : 0);
const tax = roundToCents(subtotal * rate);
return { tax, total: roundToCents(subtotal + tax), rate };
}
function roundToCents(value) {
return Math.round((value + Number.EPSILON) * 100) / 100;
}
A few things worth noticing:
- Rounding once, at the end. Rounding each line item separately and then summing can drift by a cent. Round the tax, round the total, and move on.
-
Number.EPSILONguards against the classic0.1 + 0.2floating-point surprise when a value sits exactly on a half-cent boundary. -
The
exemptoption is how you model tax-free items. The caller decides what is exempt; the engine just honours it.
Usage is straightforward:
const result = calculateSalesTax(250, "CA");
console.log(result);
// { tax: 21.70, total: 271.70, rate: 0.0868 }
const oregon = calculateSalesTax(250, "OR");
console.log(oregon);
// { tax: 0, total: 250, rate: 0 }
Step 3: Reverse Calculation β Tax-Inclusive Prices
Some shops show prices that already include tax. To extract the tax from an inclusive price, divide instead of multiply:
function extractTaxFromInclusive(inclusivePrice, stateCode) {
const state = STATE_RATES[stateCode.toUpperCase()];
if (!state) throw new Error(`Unknown state code: ${stateCode}`);
const rate = state.state + state.localAvg;
if (rate === 0) return { tax: 0, net: inclusivePrice, rate: 0 };
const net = roundToCents(inclusivePrice / (1 + rate));
return { tax: roundToCents(inclusivePrice - net), net, rate };
}
This is the same maths a VAT calculator uses, and it is easy to get wrong by subtracting price * rate instead of dividing β that mistake overstates the tax.
Edge Cases That Break Real Implementations
1. Nexus and marketplace facilitator laws. Since the 2018 South Dakota v. Wayfair decision, an online seller may owe tax in a state where they have no office, purely because of sales volume there. A lookup engine answers "what is the rate?" β it cannot answer "do I owe tax here?" Do not conflate the two.
2. Origin vs. destination sourcing. Most states tax based on where the buyer is (destination sourcing); a few, including Texas and Ohio, tax based on where the seller ships from (origin sourcing). If your app ships physical goods, the sourcing rule changes which rate applies.
3. ZIP code is not a tax jurisdiction. A single ZIP code can span multiple counties with different rates. For exact checkout tax, resolve the full address, not the ZIP alone.
4. Rate changes mid-year. Rates are usually updated on 1 January and 1 July. Store a lastUpdated date with your table and refresh it on a schedule β a stale table silently over- or under-charges every customer.
5. Rounding on multi-item carts. Calculate tax per line item or on the cart total? Most jurisdictions tax the total sale, but some require per-item rounding. Pick one, document it, and be consistent β a one-cent mismatch between your receipt and a customer's expectation is a support ticket waiting to happen.
Making the Table Maintainable
A hard-coded object is fine for a tutorial, but in a real app, pull the rates from a data source:
// rates.json β generated from a tax authority feed, versioned in git
async function loadRates() {
const response = await fetch("/data/sales-tax-rates.json");
const { version, updated, rates } = await response.json();
console.log(`Sales tax rates v${version}, updated ${updated}`);
return rates;
}
Versioning the data separately from the code means a rate change is a data deploy, not a code deploy β and your tests can pin a known version so a rate update never silently changes a test expectation.
Conclusion
US sales tax is a data problem wearing a maths problem's clothes. The calculation is two lines; the hard part is keeping the lookup accurate, handling exemptions, and knowing when an estimate is good enough and when only an exact address-level rate will do.
Build the engine as data plus logic, round once, and keep the table versioned. And when you just need the answer for a purchase, the free US Sales Tax Calculator handles the lookup β including the five no-tax states β in a single click.
Rates in this article are state base rates plus average local rates, current for 2026. Always verify the exact rate for a real transaction against the state's tax authority.
Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes β full credit and traffic to the original publisher.