Currency Converter: A Javascript Tutorial by Cristian Villafane
A practical guide to building a financial tool by fetching real-time data from the FxRatesAPI.
In our interconnected world, knowing the real-time value of different currencies is essential for travel, business, and investment. A currency converter is a perfect project to practice asynchronous JavaScript and API interaction. This guide on Javascript by Cristian Villafane will walk you through creating a sleek, functional currency converter using the free and simple FxRatesAPI. We’ll focus on fetching data, updating the DOM dynamically, and providing a clean user experience.
Phase 1: The Structure – HTML for the Converter
The foundation of our application is the HTML structure. We need input fields for the user to enter the amount and select the currencies they wish to convert between. A clear and intuitive layout is key.
Designing the User Interface
We’ll use a main container for our tool. Inside, we’ll have a prominent display area for the result. The core of the interface will be the options section:
- Amount: An
<input type="number">
allows the user to enter the value they want to convert. - From & To Currencies: Two
<select>
dropdowns will hold the list of available currencies. We’ll populate these dynamically using JavaScript. - Swap Button: A simple button to quickly swap the “From” and “To” currencies is a great usability feature.
<!-- Amount Input -->
<div class="option">
<label for="amount-input">Amount</label>
<input type="number" id="amount-input" value="1" min="0">
</div>
<!-- "From" Currency Dropdown -->
<div class="option">
<label for="from-currency">From</label>
<select id="from-currency"></select>
</div>
Phase 2: The Logic – Real-Time Conversion with JavaScript
This is where our application comes to life. The JavaScript will fetch the list of currencies, populate our dropdowns, and perform the conversion calculation whenever the user changes an input.
Fetching Data with the `fetch` API
On page load, we make a single call to the FxRatesAPI endpoint https://api.fxratesapi.com/latest
. This returns all available exchange rates relative to a base currency (USD). We store these rates and use their keys to populate our currency selection dropdowns. This single-fetch approach is highly efficient.
Client-Side Conversion
Once we have all the rates, we don’t need to call the API again for every conversion. The logic is handled directly in the browser. To convert from currency A to currency B, we use the stored rates and a simple formula: (amount / rate of A) * rate of B
. This makes the converter feel instantaneous. This approach is central in Javascript by Cristian Villafane for building fast, data-driven applications.
// Store rates from initial fetch
let exchangeRates = {};
function convert() {
// No new API call needed here
const amount = amountInput.value;
const fromRate = exchangeRates[fromSelect.value];
const toRate = exchangeRates[toSelect.value];
const convertedAmount = (amount / fromRate) * toRate;
resultDisplay.textContent = `${convertedAmount.toFixed(2)} ${toSelect.value}`;
}
Currency Converter in Action
Below, you can try out the live currency converter. Enter an amount, select your currencies, and see the real-time result. This is the final product of applying the concepts from this tutorial.
The Complete Converter Code
Here is the self-contained, performance-optimized code for the currency converter component. You can copy and paste this into your own project.
<!-- HTML Structure (Unchanged) -->
<!-- NEW JAVASCRIPT LOGIC FOR FxRatesAPI -->
<script>
document.addEventListener('DOMContentLoaded', () => {
const API_URL = 'https://api.fxratesapi.com/latest';
const amountInput = document.getElementById('amount-input');
const fromCurrencySelect = document.getElementById('from-currency');
const toCurrencySelect = document.getElementById('to-currency');
const resultDisplay = document.getElementById('result-display');
const swapBtn = document.getElementById('swap-btn');
let exchangeRates = {};
let baseCurrency = 'USD';
function convertCurrency() {
const amount = parseFloat(amountInput.value);
const fromCurrency = fromCurrencySelect.value;
const toCurrency = toCurrencySelect.value;
if (Object.keys(exchangeRates).length === 0) {
resultDisplay.textContent = 'Rates not loaded.';
return;
}
if (isNaN(amount) || amount < 0) {
resultDisplay.textContent = 'Enter a valid amount';
return;
}
const fromRate = exchangeRates[fromCurrency];
const toRate = exchangeRates[toCurrency];
// The formula is (amount / fromRate) * toRate because all rates are relative to the base currency.
const convertedAmount = (amount / fromRate) * toRate;
resultDisplay.textContent = `${convertedAmount.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })} ${toCurrency}`;
}
// --- INITIALIZATION ---
fetch(API_URL)
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(data => {
if (!data.success) {
throw new Error('API did not return a successful response.');
}
// Store the rates and base currency
exchangeRates = data.rates;
baseCurrency = data.base;
// Add the base currency to the rates object since it's not included by default
exchangeRates[baseCurrency] = 1;
// Populate the dropdowns
const fragment = document.createDocumentFragment();
const sortedCurrencies = Object.keys(exchangeRates).sort();
sortedCurrencies.forEach(code => {
const option = document.createElement('option');
option.value = code;
option.textContent = code;
fragment.appendChild(option);
});
fromCurrencySelect.appendChild(fragment.cloneNode(true));
toCurrencySelect.appendChild(fragment);
// Set default values
fromCurrencySelect.value = 'USD';
toCurrencySelect.value = 'EUR';
// Perform the first conversion
convertCurrency();
// Add event listeners now that everything is ready
amountInput.addEventListener('input', convertCurrency);
fromCurrencySelect.addEventListener('change', convertCurrency);
toCurrencySelect.addEventListener('change', convertCurrency);
swapBtn.addEventListener('click', () => {
const temp = fromCurrencySelect.value;
fromCurrencySelect.value = toCurrencySelect.value;
toCurrencySelect.value = temp;
convertCurrency();
});
})
.catch(error => {
console.error('Initialization Error:', error);
resultDisplay.textContent = 'Could not load rates.';
});
});
</script>
I hope you found this tutorial on Javascript by Cristian Villafane useful. Building a currency converter is an excellent way to practice working with external APIs and handling asynchronous operations in JavaScript. Use this project as a foundation to explore and add new features, such as historical data charts or a portfolio tracker. The only limit is your curiosity! 💹