Finding hamming distance in a string in JavaScript

The Hamming distance between two strings of equal length is the number of positions at which the corresponding characters differ. It measures the minimum number of single-character edits needed to transform one string into another.

In JavaScript, we can calculate Hamming distance by comparing each character position and counting the differences. This metric is commonly used in coding theory, cryptography, and bioinformatics.

Basic Implementation

Here's a JavaScript function that calculates the Hamming distance between two strings:

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()) {
                distance++;
            }
        }
        return distance;
    }
    return 0; // Return 0 if lengths don't match
};

console.log(findHammingDistance(str1, str2));
3

In this example, the strings differ at positions 2 ('l' vs 'e'), 3 ('l' vs 'y'), and 4 ('o' vs 'y'), giving a Hamming distance of 3.

Case-Sensitive Version

For case-sensitive comparison, simply remove the toLowerCase() calls:

const findHammingDistanceCaseSensitive = (str1, str2) => {
    if (str1.length !== str2.length) {
        return -1; // Return -1 for invalid input
    }
    
    let distance = 0;
    for (let i = 0; i < str1.length; i++) {
        if (str1[i] !== str2[i]) {
            distance++;
        }
    }
    return distance;
};

console.log(findHammingDistanceCaseSensitive('Hello', 'hello'));
console.log(findHammingDistanceCaseSensitive('abc', 'def'));
1
3

Using Array Methods

An alternative approach using array methods and reduce:

const hammingDistanceArray = (str1, str2) => {
    if (str1.length !== str2.length) {
        throw new Error('Strings must have equal length');
    }
    
    return str1
        .split('')
        .reduce((distance, char, index) => {
            return distance + (char !== str2[index] ? 1 : 0);
        }, 0);
};

try {
    console.log(hammingDistanceArray('karolin', 'kathrin'));
    console.log(hammingDistanceArray('1011101', '1001001'));
} catch (error) {
    console.log(error.message);
}
3
2

Comparison of Approaches

Method Performance Readability Error Handling
For Loop Fastest Good Basic
Array Reduce Slower Functional Exception-based

Common Use Cases

Hamming distance is useful for:

  • DNA sequence comparison in bioinformatics
  • Error detection in digital communications
  • Spell checking and string similarity algorithms
  • Quality assessment in data transmission

Conclusion

Hamming distance provides a simple metric for comparing strings of equal length. The for-loop approach offers the best performance, while array methods provide more functional programming style. Always validate that input strings have equal length before calculation.

Updated on: 2026-03-15T23:19:00+05:30

675 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements