How to make a currency converter using vanilla Javascript ?

How to make a currency converter using vanilla Javascript ?

Recently, I have made a currency converter as a part of Scrimba's Weekly web dev challenge, using vanilla Javascript, and so I have decided to share how I built it out.

About Scrimba :

Scrimba is an amazing platform for those who want to learn web development . It has a feature that allows us to edit the instructor's code and play around with the code which in turn helps to quickly grasp the topics being taught! At Scrimba, they also emphasize the fact that learning in public can help you become a better developer as it helps in building self-confidence as well as you can find ways to improve your skills...

Getting Started

Firstly, for the HTML part, we need

  • an input of type "number" for entering the amount to be converted

  • two drop-down menus to select the original currency unit and the new currency unit, the options for the two will be generated dynamically using Javascript fetch API.

  • another disabled input for displaying the exchange rate dynamically, based on the currency units selected...

  • a button element , which when clicked will do the conversion and will display the results

  • a paragraph element for displaying the results of conversion...

For the styling part , you can do it in your own way, I have done it by aligning all the elements to the center, the background has a image depicting currencies of different countries,adjusting font-size, giving all inputs a border-radius and some padding, and at last styling the button by giving it a background-color and some hover effects.

Now the main part, fetching currency units and exchange rates from API. I have used exchangerates API to fetch the currency units and their exchange rates. Firstly, we have to provide to the user, a list of currency codes to choose from, therefore we'll create a function that will do the task...

const createOptions= async ()=>{
    const url= 
    'https://api.exchangeratesapi.io/latest';
try{
    const response = await fetch(url);
    const data = await response.json();
    let {rates}=data;
    for(let currencyCode in rates){
        let optionForOriginal = new Option(currencyCode,currencyCode);
         let optionForNew = new Option(currencyCode,currencyCode);
        originalCurrencyUnit.add(optionForOriginal);
        newCurrencyUnit.add(optionForNew);
    }
}catch(e){
    console.log("Oops! error: ",e);
}
}

Here we have a createOptions function which is a asynchronous function because we are using fetch( ) which returns a promise. As we get a response object ,we convert it to JSON format using response.json( ) method. Here is the response we get from the API:

{"rates":{"CAD":1.5413,"HKD":9.4005,"ISK":156.4,"PHP":58.226,"DKK":7.4393,"HUF":359.99, "CZK":26.163,"AUD":1.568,"RON":4.8733,"SEK":10.1305,"IDR":17032.57,"INR":88.6365, "BRL":6.3697,"RUB":89.0364,"HRK":7.5535,"JPY":125.74,"THB":36.411,"CHF":1.077, "SGD":1.6105,"PLN":4.5375,"BGN":1.9558,"TRY":9.0179,"CNY":7.8499,"NOK":10.3135, "NZD":1.6896,"ZAR":18.4627,"USD":1.2123,"MXN":24.0231,"ILS":3.9546, "GBP":0.88998,"KRW":1333.6,"MYR":4.8939},"base":"EUR","date":"2021-01-15"}}

As you can see, we have a "rates" object which contains currency codes and corresponding exchange rates. For creating options for currency units presently,we just need currency codes. And therefore we iterate through the "rates" object using for...in loop. To create new option element, we use Option constructor which takes text and value as parameters. The newly created options are then added to select element using add() method.

Next, we need to display the exchange rate as well as exchanged amount, we have to create another function which performs the conversion and display the results..

async function convert(){

let baseUnit,newCurrency;
baseUnit=originalCurrencyUnit.value;
newCurrency=newCurrencyUnit.value;
const url= 
`https://api.exchangeratesapi.io/latest?base=${baseUnit}&symbols=${newCurrency}`;
try{
    const response = await fetch(url);
    const data = await response.json();
    let {rates}=data;
    let exchangeRateValue=rates[newCurrency];
    exchangeRate.value=exchangeRateValue.toFixed(2);
    let convertedAmount= originalCurrencyAmount.value * exchangeRateValue;
    outputText.textContent=
  `Your ${baseUnit} ${originalCurrencyAmount.value} will currently buy you ${newCurrency} ${convertedAmount.toFixed(2)}`;
}catch(e){
    console.log("Oops error: ",e);
}
}

We have used the same endpoint but this time, we have passed parameters. The "base" parameter allows you to set a different base unit for the exchange rates which is by default "EUR" and "symbols" parameter allows you to fetch the exchange rates of specific currency unit. Here base is set to the original currency unit and the symbols parameter is set equal to the new currency unit which we entered in their respective input fields. Therefore, we get the exchange rate of new currency unit with respect to original currency unit. In order to convert the entered amount to new currency amount, we simply multiply the amount with the exchange rate. And lastly we display the results.

You can get the complete code here .

This was all from my side... Thanks for reading till the end. I hope this helps. GoodBye and Keep Coding :)