Convert Kilometers to Miles using JavaScript #javascriptprogramming #webdevelopmenttutorial

Posted by

JavaScript Program to Convert Kilometers to Miles

JavaScript Program to Convert Kilometers to Miles

In this tutorial, we will create a simple JavaScript program to convert kilometers to miles. We will use HTML for the user interface and JavaScript for the conversion logic.

HTML

First, let’s create an HTML form to take input from the user and a button to trigger the conversion:

    
      <form>
        <label for="kilometers">Enter kilometers:</label>
        <input type="number" id="kilometers" name="kilometers">
        <button onclick="convertKilometersToMiles()">Convert</button>
      </form>
    
  

JavaScript

Now, let’s write the JavaScript function convertKilometersToMiles to perform the conversion:

    
      <script>
        function convertKilometersToMiles() {
          var kilometers = document.getElementById('kilometers').value;
          var miles = kilometers * 0.621371;

          alert(kilometers + ' kilometers is equal to ' + miles + ' miles.');
        }
      </script>
    
  

Now, when the user enters a value in kilometers and clicks the “Convert” button, the convertKilometersToMiles function will be called, and an alert will display the converted value in miles.

Conclusion

With just a few lines of HTML and JavaScript, we have created a simple program to convert kilometers to miles. This is a basic example of using JavaScript to perform calculations and interact with the user in a web application.