Write a JavaScript Program to Convert Kilometers to Miles

In programming, converting units is a common task. In this tutorial, we will write a JavaScript program to convert kilometers to miles.

To start with, let’s define what a kilometer and a mile are. A kilometer is a unit of length in the metric system, equivalent to 1000 meters, while a mile is a unit of length in the imperial and US customary systems, equal to 5280 feet or approximately 1.609 kilometers.

Now that we know the definition of the two units let’s write the code.

To convert kilometers to miles, we need to multiply the number of kilometers by 0.621371192, which is the conversion factor. Here is the JavaScript code to convert kilometers to miles:

function convertKilometersToMiles(kilometers) {
  const conversionFactor = 0.621371192;
  const miles = kilometers * conversionFactor;
  return miles;
}

This code defines a function called convertKilometersToMiles that takes in a parameter called kilometers.

The function then multiplies the kilometers parameter by the conversion factor and assigns the result to the miles variable. Finally, the function returns the miles variable.

We can use this function to convert any number of kilometers to miles. For example, if we want to convert 10 kilometers to miles, we can call the convertKilometersToMiles function and pass in 10 as the argument:

const kilometers = 10;
const miles = convertKilometersToMiles(kilometers);
console.log(`${kilometers} kilometers is equal to ${miles} miles.`);

This code defines a variable called kilometers and assigns it a value of 10.

It then calls the convertKilometersToMiles function, passing in kilometers as the argument, and assigns the result to a variable called miles.

Finally, it logs the result to the console using a template literal.

That’s it! Now you can easily convert kilometers to miles using JavaScript.