Hamming Distance between two strings in JavaScript

Hamming Distance

The Hamming distance between two strings of equal length is the number of positions at which the corresponding symbols are different.

For example, consider the following strings −

const str1 = 'delhi';
const str2 = 'delph';

The Hamming Distance of these strings is 2 because the fourth and the fifth characters of the strings are different. And obviously in order to calculate the Hamming Distance we need to have two strings of equal lengths.

Therefore, we are required to write a JavaScript function that takes in two strings, let’s say str1 and str2, and returns their hamming distance.


Following is the code −

const str1 = 'delhi';
const str2 = 'delph';
const hammingDistance = (str1 = '', str2 = '') => {
   if (str1.length !== str2.length) {
      return 0;
   let dist = 0;
   for (let i = 0; i < str1.length; i += 1) {
      if (str1[i] !== str2[i]) {
         dist += 1;
   return dist;
console.log(hammingDistance(str1, str2));


Following is the output on console −


Updated on: 11-Dec-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started