Finding hamming distance in a string in JavaScript

Hamming Distance:

The hamming distance between two strings of equal length is the number of positions at which these strings vary.

In other words, it is a measure of the minimum number of changes required to turn one string into another. Hamming Distance is usually measured for strings equal in length.

We are required to write a JavaScript function that takes in two strings, lets say str1 and str2, of the same length. The function should calculate and return the hamming distance between those strings.


Following is the code −

const str1 = 'Hello World';
const str2 = 'Heeyy World';
const findHammingDistance = (str1 = '', str2 = '') => {
   let distance = 0;
   if(str1.length === str2.length) {
      for (let i = 0; i < str1.length; i++) {
         if (str1[i].toLowerCase() != str2[i].toLowerCase()){
      return distance
   return 0;
console.log(findHammingDistance(str1, str2));


Following is the console output −