Haversine formula to calculate distances

I made my own implementation of the haversine formula to calculate distances between to coordinates but it gave me wrong calculation. Maybe that’s something wrong. Can anyone please help me to improve it?

inputs.coords gets a list of coordinates filled by the latest geopoller data by this set

WITH_ITEM(pageVars.coords, {point: {type: “point”, data: {lat: sensorVars.geolocation.latestValue.latitude, lng: sensorVars.geolocation.latestValue.longitude}}, accuracy: sensorVars.geolocation.latestValue.accuacy, altitude: sensorVars.geolocation.latestValue.altitude, altitude_accuracy: sensorVars.geolocation.latestValue.altitudeAccuracy, speed: sensorVars.geolocation.latestValue.speed, heading: sensorVars.geolocation.latestValue.heading, created_at: sensorVars.geolocation.latestValue.timestamp, accuracy: sensorV

let d = 0;
try {
const coordsSize = inputs.coordsSize;
if (coordsSize > 1 ){
const lat2 = inputs.coords[coordsSize - 1].point.data.lat;
const lon2 = inputs.coords[coordsSize - 1].point.data.lng;
const lat1 = inputs.coords[coordsSize - 2].point.data.lat;
const lon1 = inputs.coords[coordsSize - 2].point.data.lng;

const R = 6371; // km 
//has a problem with the .toRad() method below.
const x1 = lat2-lat1;
let dLat = x1 * Math.PI / 180;
const x2 = lon2-lon1;
let dLon = x2 * Math.PI / 180;
const a = Math.sin(dLat/2) * Math.sin(dLat/2) + 
                Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) * 
                Math.sin(dLon/2) * Math.sin(dLon/2);  
const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); 
d = R * c;
if (d > 0){
  console.log("Result in meters: " + d);
}
return [0, { result: d}];

} else {
return [0, { result: 0}];
}
} catch (err) {
console.log("error: "+err);
const error = {
code: ‘unknownError’,
message: ‘Something went wrong.’,
rawError: err,
}

return [1, { error }]
}