Convert Kilometres to Miles – Javascript Program

This is a preview lesson
Register or sign in to take this lesson.

Kilometres to Miles and Vice-versa

This tutorial shows a snippet for finding the solution for converting Kilometres to Miles and the other way around.
The unit conversion from Kilometre to Mile is: 1 km = 0.621371 mile
The unit conversion from Mile to Kilometre is: 1 mile = 1.60934 km

Pseudo-code

// Kilometre to Mile
kilometreToMile = kilometres  *  0.621371

// mile to kilometer
mileToKilometres = miles  *  1.60934

JavaScript Syntax

let kilometreToMile = kilometres * 0.621371;

let mileToKilometres = miles * 1.60934;

Firstly, let’s look at assigning it to a variable after calculation.

// Kilometres to Mile
let kilometres = 10;
const unitMile = 0.621371;

let kilometreToMile = kilometres * unitMile;

console.log(kilometreToMile);          
/*
 * Output
 * prints 6.21371 miles which is the conversion of 10 kilometres  
*/

// Mile to Kilometres
let miles = 10;
const unitKilometre = 1.60934;

let mileToKilometre = miles * unitKilometre;

console.log(mileToKilometre);          
/*
 * Output
 * prints 16.0934 Kilometres which is the conversion of 10 Miles  
*/

Now, the same code wrapped inside function looks like

// function that converts kilometres to miles
function kilometreToMile(kilometre) {
    const unitMile = 0.621371;
    return kilometres* unitMile;
}

// function that converts miles to kilometres
function mileToKilometre(mile) {
    const unitKilometre = 1.60934;
    return mile * unitKilometre;
}


console.log(kilometreToMile(10));
/*
 * Output
 * prints 6.21371 miles which is the conversion of 10 kilometres  
*/


console.log(mileToKilometre(10));
/*
 * Output
 * prints 16.0934 Kilometres which is the conversion of 10 Miles  
*/