Course offer · HLD · LLD · System Design at ₹799 until 30 Nov (not interview packs)

Anagram Check in JavaScript

Check if two strings are anagrams in JavaScript by sorting letters or counting them. "listen" and "silent" match. Full explanation, gotchas and output.

IntermediateJavaScript String ProgramsExample 4 of 5
anagram-check.js
1// Anagram: Same characters, different order
2// Examples: "listen" and "silent", "evil" and "vile"
3
4// Method 1: Sort and compare
5function isAnagram1(str1, str2) {
6 // Normalize: lowercase, remove spaces
7 str1 = str1.toLowerCase().replace(/\s/g, '');
8 str2 = str2.toLowerCase().replace(/\s/g, '');
9
10 // Sort and compare
11 return str1.split('').sort().join('') ===
12 str2.split('').sort().join('');
13}
14
15console.log("listen & silent:", isAnagram1("listen", "silent"));
16console.log("hello & world:", isAnagram1("hello", "world"));
17console.log("The Morse Code & Here come dots:",
18 isAnagram1("The Morse Code", "Here come dots"));
19
20// Method 2: Character frequency count
21function isAnagram2(str1, str2) {
22 str1 = str1.toLowerCase().replace(/\s/g, '');
23 str2 = str2.toLowerCase().replace(/\s/g, '');
24
25 if (str1.length !== str2.length) return false;
26
27 let count1 = {};
28 let count2 = {};
29
30 // Count characters in str1
31 for (let char of str1) {
32 count1[char] = (count1[char] || 0) + 1;
33 }
34
35 // Count characters in str2
36 for (let char of str2) {
37 count2[char] = (count2[char] || 0) + 1;
38 }
39
40 // Compare counts
41 for (let char in count1) {
42 if (count1[char] !== count2[char]) {
43 return false;
44 }
45 }
46
47 return true;
48}
49
50console.log("\nUsing frequency:");
51console.log("listen & silent:", isAnagram2("listen", "silent"));
52console.log("aabb & abab:", isAnagram2("aabb", "abab"));
53
54// Method 3: Single object count
55function isAnagram3(str1, str2) {
56 str1 = str1.toLowerCase().replace(/\s/g, '');
57 str2 = str2.toLowerCase().replace(/\s/g, '');
58
59 if (str1.length !== str2.length) return false;
60
61 let count = {};
62
63 // Increment for str1
64 for (let char of str1) {
65 count[char] = (count[char] || 0) + 1;
66 }
67
68 // Decrement for str2
69 for (let char of str2) {
70 if (!count[char]) return false;
71 count[char]--;
72 }
73
74 return true;
75}
76
77console.log("\nSingle object:");
78console.log("evil & vile:", isAnagram3("evil", "vile"));

Sample Output

listen & silent: true
hello & world: false
The Morse Code & Here come dots: true

Using frequency:
listen & silent: true
aabb & abab: true

Single object:
evil & vile: true

In this one

  • What makes two words anagrams
  • How sorting letters gives a fingerprint
  • How to count letters with an object
  • Why you normalise case and spaces first

How it works

  1. 1

    Both words are lowercased and spaces removed.

  2. 2

    Sorting gives "eilnst" for listen and silent.

  3. 3

    hello and world sort differently, so false.

  4. 4

    Frequency counts match for aabb and abab.

  5. 5

    The single-object method confirms evil and vile.

Edge cases

Different lengths

"abc" and "abcc" are not anagrams.

Methods 2 and 3 check length first and return false early.

Punctuation

"dormitory!" vs "dirty room" fails.

Only spaces are removed here. Strip punctuation with a wider regex if needed.

Same word twice

isAnagram1("cat", "cat") is true.

By this rule a word is its own anagram. Add a check if you want different words.

What's going on

Two words are anagrams if they use the same letters the same number of times, in any order. "listen" and "silent" are anagrams. So are "evil" and "vile".

All methods first normalise the text. toLowerCase() stops "Listen" and "silent" from failing over one capital letter. replace(/\s/g, '') removes spaces, so phrases like "The Morse Code" and "Here come dots" can match. Whether spaces should count is your choice. This page strips them.

Method 1 sorts. It splits each string into letters, sorts them, and joins them back. "listen" and "silent" both become "eilnst". If the two sorted strings are equal, they are anagrams. It is short and easy to trust.

Method 2 counts letters. It builds an object for each word, where each key is a letter and each value is how many times it appears. (count1[char] || 0) + 1 starts a new letter at 0 and adds 1. Then it compares the two counts. It checks lengths first, so a word with extra letters fails fast.

Method 3 uses one object. It adds 1 for each letter of the first word and subtracts 1 for each letter of the second. If a letter is missing or runs out, !count[char] is true and the answer is false.

Counting is faster than sorting for long strings. Sorting is simpler to read.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

Are "night" and "thing" anagrams?

Pick an answer to check it.

Question 2

What does "cab".split("").sort().join("") return?

Pick an answer to check it.

Questions people ask

Why sort the letters?

Sorting puts letters in a fixed order. Anagrams end up as the same string.

What does (count[char] || 0) mean?

If the letter has no count yet, use 0. Then add 1.

Which method should I use?

Sorting for clarity. Counting for long text.