Distance Unit Converter Javascript Feedback wanted

Hello,

I am a beginner at Javascript and coded the following program :

const transformUnit = (amount, unit) => { //Here is checked if the amount and unit are filled. Unit is send to lowercase for less if statements if (amount === undefined) { console.log("Please insert any amount you want to have converted"); } else if (unit === undefined) { console.log( "Please enter the Unit you want to convert. You can choose between Kilometers, Meters and Centimeters" ); } else { //converting Unit into a resuable lower case unit unitLow = unit.toLowerCase(); } //declaring a calculation variable to call amout in the outout statement, calc = amount; calc2 = calc; // this converts calc so that i can have the //Further If that grabs the converted unit and does the calculation if (unitLow === "kilometer") { meter = calc *= 1000; centimeter = calc2 *= 100000; console.log( `Your initial amount was ${amount} in the Unit: ${unit}. Converted it is ${meter} Meters and ${centimeter} Centimeters.` ); } else if (unitLow === "meter") { kilometer = calc /= 1000; centimeter = calc2 *= 100; console.log( `Your initial amount was ${amount} in the Unit: ${unit}. Converted it is ${kilometer} Kilometers and ${centimeter} Centimeters.` ); } else if (unitLow === "centimeter") { kilometer = calc /= 100000; meter = calc2 /= 100; console.log( `Your initial amount was ${amount} in the Unit: ${unit}. Converted it is ${kilometer} Kilometers and ${meter} Meters.` ); } }; //function is called here transformUnit(50, "Centimeter");

I had to convert amout into calc and then into calc 2 in line 14 and 15 otherwise the parameters would have been overwritten in the calculation and produced strange values in the output.

Is there any smarter way to deal with this issue?

Thanks for your input in advance!

You did not have to change the value of calc in your code;
you have

    meter = calc *= 1000;
    centimeter = calc2 *= 100000;

but you could have done

    meter = calc * 1000;
    centimeter = calc * 100000;

so that the number in calc doesn’t change.

1 Like

Yeah I used to have it only once but then within the calculation it was overwritten. Thanks for your remark. I´ll give it a try!