0

I'm doing a program which converts currencies and measures. To make the code more reusable I've created a function which shows the symbols on a dropdown and get the rate from an API. This is the code:

const firstDropdown = document.querySelector('.first-value');
const secondDropdown = document.querySelector('.second-value');
const firstSymbol = document.querySelector('.first-symbol-button');
const secondSymbol = document.querySelector('.second-symbol-button');
const firstInput = document.querySelector('.first-value-input');
const secondInput = document.querySelector('.second-value-input');


//FUNCTIONS
const showSymbolsAndGetRates = (event, symbol, rate) => {
    if(event.target.tagName === 'A'){
        symbol.innerText = event.target.innerText;
        rate = currencies.rates[event.target.innerText];
    };
    return rate;
}

//get symbols and rates
let firstRate = 'ciao';
let secondRate = 'ciao';

firstDropdown.addEventListener('click', e => {
    e.preventDefault();
    showSymbolsAndGetRates(e, firstSymbol, firstRate);

    // if(e.target.tagName === 'A'){
    //     firstSymbol.innerText = e.target.innerText;
    //     firstRate = currencies.rates[e.target.innerText];
    //     return firstRate;
    // };
    console.log(firstRate)
});
secondDropdown.addEventListener('click', e => {
    e.preventDefault();
    showSymbolsAndGetRates(e, secondSymbol, secondRate);
    // if(e.target.tagName === 'A'){
    //     secondSymbol.innerText = e.target.innerText;
    //     secondRate = currencies.rates[e.target.innerText];
    // }
    // return secondRate;
    console.log(secondRate)
});

As you can see the code in the function showSymbolsAndGetRates is the same as the commented code, which was the original code. The problem is that when I use the commented code the rate is returned without problems but when I use the function the rate does not change, so the console shows 'ciao' instead of the real rate. I'm new at programming and I have no idea of how to solve this problem without having to write code for every event.

Connell.O'Donnell
  • 3,603
  • 11
  • 27
  • 61
matteo
  • 115
  • 1
  • 7
  • "The problem is that when I use the commented code the rate is returned without problems" — How do you know? It is returned to the internal browser code which triggered the event listener. How are you inspecting that to tell that it works? – Quentin Feb 07 '21 at 12:08
  • The only code which modifies `firstRate` or `secondRate` is commented out. If you want to change the value of those variables you need to assign new values *to those variables*. The `showSymbolsAndGetRates` only assigns a new value to the local `rate` variable, which you return and then ignore. – Quentin Feb 07 '21 at 12:11
  • try `firstRate = showSymbolsAndGetRates(e, firstSymbol, firstRate);` so that you actually use the calculation that is returned. – Claies Feb 07 '21 at 12:13
  • thanks to both of you. – matteo Feb 07 '21 at 13:21

0 Answers0