I have a problem with the '+=' operator in NodeJs: when I add a number variable to an another number variable it combine them together

const ricarica = (conto, deposito) => {
    deposito = prompt("Quanti soldi vuole depositare sul suo conto? ");
    
    conto += deposito;
    return console.log(`Ora il suo conto ha una disponibilità residua di ${conto}€`);
}

If the ‘conto’ statement is equal to 0 and ‘deposito’ is equal to 200, the final output is 0200.

I’ve tried to convert ‘deposito’ and ‘conto’ into float values but nothing changed.

Please help me to solve this problem 🥺

>Solution :

Since Javascript is loosely-typed, it is viewing conto and deposito as strings and appending them. Convert the to numbers before performing the addition:

let a = Number.parseInt(conto);
let b = Number.parseInt(deposito);
a += b;

Leave a Reply