Whether you're trying to figure out how to best sow the seeds for your financial future, or you simply need to track down a straightforward compound-interest.js formula, this post has you covered.
I love experimenting with compound interest formulas. A few months ago (aka pre-covid confinement 😷), I wanted to figure out the long-term cost of eating lunch out during the work week should I invest the money instead.
I was full and a bit sleepy when I got back from lunch. I would have rather taken a nap, but instead learned that cutting 2 weekly lunches out during the work week could net $10k in 30 years.
I'm never going to give up the occasional sandwich or bowl of ramen out, and I don't think you should either - life's too short! But, I don't mind missing out on the post meal grogginess that often accompanies a carbohydrate rich lunch while padding my savings from time to time.
Playing around with compound interest rate formulas can provide interesting fodder when you've got a few minutes to burn and money on your mind. Once familiar with the formula, it's easy enough to play around with the calculations in your browser's console. You can use the formulas for simple things, like figuring out how much you're blowing on lunch or coffee each week. Or, you can start with a simple compound interest formula and the JavaScript console to plot your entire fiscal future.
Let's look at a basic example of a function to figure out how much today's lunch money is worth tomorrow 🥪
Calculating Compound Interest in JavaScript
We're going to use this formula as the basis of our JavaScript compound interest logic.
A: Accrued Amount (principal + interest)
P: Principal
r: Interest Rate
n: Number of times the interest is applied per time period
t: number of time periods elapsed
JavaScript doesn't know algebra. We'll need to use the multiplication operator (*
) and Math.pow() to write our compound interest formula.
A basic example using the same variables as the above equation looks something like this in JavaScript -
JavaScript Compound Interest Formula
A = P * Math.pow(1 + r / n, nt);
A JS Compound Interest Function
In practice, it may be easier if we create a function and use human readable variable names.
function calcCompoundInterest(principal, rate, frequency, years) {
return principal * Math.pow(1 + rate / frequency, frequency * years);
}
Now, we can take our calcCompoundInterest()
function to explore various combination of investment principal, projected returns, and time horizon.
Let's return to my original use case, figuring out how the true cost of a sandwich habit, to test it out. I encourage you to copy and paste these examples into your browser console to follow along!
function calcCompoundInterest(principal, rate, frequency, years) {
return principal * Math.pow(1 + rate / frequency, frequency * years);
}
const pricePerSandwich = 10;
const sandwichesBoughtPerWeek = 3;
const workWeeksPerYear = 50;
const sandwichTotalCost =
pricePerSandwich * sandwichesBoughtPerWeek * workWeeksPerYear;
// Let's optimistically expect a 10% return on our investment
const rate = 0.1;
// Assume our investment compounds 4 times per year, once each fiscal quarter
const frequency = 4;
// What is the cost of 150 sandwiches ten years from now?
const years = 10;
const tenYearValue = calcCompoundInterest(
sandwichTotalCost,
rate,
frequency,
years
);
console.log(tenYearValue); // 4027.5957575849507
Our compound interest function doesn't return the accrued amount formatted for local currency. Let's add a couple of convenience methods to format our returned value for display.
To do this, we'll use JavaScript's Intl.NumberFormat to add a $
currency symbol and reduce the number of decimals. Once formatted our tenYearValue
should be output as $4,027.60
.
Building on the previous example,
function formatCurrency(value) {
const formatter = new Intl.NumberFormat("en-US", {
style: "currency",
currency: "USD",
});
return formatter.format(value);
}
const thirtyYearValue = calcCompoundInterest(
sandwichTotalCost,
rate,
frequency,
years * 3
);
console.log(`
One year's sandwich 🥪 budget of ${formatCurrency(
sandwichTotalCost
)} invested:
In 10 years -> ${formatCurrency(tenYearValue)}
In 30 years -> ${formatCurrency(thirtyYearValue)} 💸
`);
Putting it All Together
It's hard to put a price on an amazing sandwich. But, our simple compound interest JavaScript function makes it a bit easier.
Take, expand, and abstract this basic function into a range of JavaScript applications and services. Figure out what your portfolio will look like after ten years of monthly contributions. Or, build something more ambitious. Whatever your use case, our calcCompoundInterest()
function is a solid start.
Here's everything above organized in a single script for greater clarity,
function formatCurrency(value) {
const formatter = new Intl.NumberFormat("en-US", {
style: "currency",
currency: "USD",
});
return formatter.format(value);
}
function calcCompoundInterest(principal, rate, frequency, years) {
return principal * Math.pow(1 + rate / frequency, frequency * years);
}
const pricePerSandwich = 10;
const sandwichesBoughtPerWeek = 3;
const workWeeksPerYear = 50;
const sandwichTotalCost =
pricePerSandwich * sandwichesBoughtPerWeek * workWeeksPerYear;
// Let's optimistically expect a 10% return on our investment
const rate = 0.1;
// Assume our investment compounds 4 times per year, once each fiscal quarter
const frequency = 4;
// What is the cost of 150 sandwiches ten years from now?
const years = 10;
const tenYearValue = calcCompoundInterest(
sandwichTotalCost,
rate,
frequency,
years
);
const thirtyYearValue = calcCompoundInterest(
sandwichTotalCost,
rate,
frequency,
years * 3
);
console.log(`
One year's sandwich 🥪 budget of ${formatCurrency(
sandwichTotalCost
)} invested:
In 10 years: ${formatCurrency(tenYearValue)}
In 30 years: ${formatCurrency(thirtyYearValue)} 💸
`);