Differences in two strings in JavaScript

We are required to write a JavaScript function that takes in two strings and find the number of corresponding dissimilarities in the strings. The corresponding elements will be dissimilar if they are not equal at the same position.

Example Strings

Let's say the following are our strings:

const str1 = 'Hello world!!!';
const str2 = 'Hellp world111';

In this case, we need to compare each character at the same index and count how many positions have different characters.

Method 1: Using a For Loop

const str1 = 'Hello world!!!';
const str2 = 'Hellp world111';

const dissimilarity = (str1 = '', str2 = '') => {
    let count = 0;
    const maxLength = Math.max(str1.length, str2.length);
    
    for(let i = 0; i 

4
Differences at positions:
Position 4: 'o' vs 'p'
Position 11: '!' vs '1'
Position 12: '!' vs '1'
Position 13: '!' vs '1'

Method 2: Using Array Methods

const str1 = 'Hello world!!!';
const str2 = 'Hellp world111';

const dissimilarityWithArray = (str1, str2) => {
    const maxLength = Math.max(str1.length, str2.length);
    return Array.from({length: maxLength}, (_, i) => str1[i] !== str2[i])
                .filter(Boolean).length;
};

console.log(dissimilarityWithArray(str1, str2));
4

Handling Edge Cases

const dissimilarityRobust = (str1 = '', str2 = '') => {
    if (typeof str1 !== 'string' || typeof str2 !== 'string') {
        throw new Error('Both inputs must be strings');
    }
    
    let count = 0;
    const maxLength = Math.max(str1.length, str2.length);
    
    for(let i = 0; i 

2
4
0

Comparison Table

Method Readability Performance Handles Different Lengths
For Loop High Fast Yes
Array Methods Medium Slower Yes

Conclusion

The for loop approach is the most efficient way to count character differences between two strings. Always handle different string lengths by using the maximum length to ensure all positions are compared.

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

508 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements