0
0
JavascriptProgramBeginner · 2 min read

JavaScript Program to Check Anagram

To check if two strings are anagrams in JavaScript, you can use function isAnagram(str1, str2) { return str1.toLowerCase().split('').sort().join('') === str2.toLowerCase().split('').sort().join(''); } which compares sorted lowercase characters of both strings.
📋

Examples

Input"listen", "silent"
Outputtrue
Input"hello", "world"
Outputfalse
Input"Triangle", "Integral"
Outputtrue
🧠

How to Think About It

To check if two words are anagrams, think about whether they have the same letters in the same amount but in a different order. Convert both words to lowercase to ignore case differences, then split them into letters, sort those letters alphabetically, and finally compare the sorted results. If they match exactly, the words are anagrams.
📐

Algorithm

1
Convert both input strings to lowercase.
2
Split each string into an array of characters.
3
Sort both arrays alphabetically.
4
Join the sorted arrays back into strings.
5
Compare the two sorted strings for equality.
6
Return true if they are equal, otherwise false.
💻

Code

javascript
function isAnagram(str1, str2) {
  return str1.toLowerCase().split('').sort().join('') === str2.toLowerCase().split('').sort().join('');
}

console.log(isAnagram('listen', 'silent')); // true
console.log(isAnagram('hello', 'world'));   // false
console.log(isAnagram('Triangle', 'Integral')); // true
Output
true false true
🔍

Dry Run

Let's trace the example isAnagram('listen', 'silent') through the code

1

Convert to lowercase

'listen' -> 'listen', 'silent' -> 'silent'

2

Split into arrays

'listen' -> ['l','i','s','t','e','n'], 'silent' -> ['s','i','l','e','n','t']

3

Sort arrays

['l','i','s','t','e','n'] -> ['e','i','l','n','s','t'], ['s','i','l','e','n','t'] -> ['e','i','l','n','s','t']

4

Join arrays

Both become 'eilnst'

5

Compare strings

'eilnst' === 'eilnst' -> true

SteplistensilentSorted listenSorted silentComparison
1listensilent
2['l','i','s','t','e','n']['s','i','l','e','n','t']
3['e','i','l','n','s','t']['e','i','l','n','s','t']
4'eilnst''eilnst'
5true
💡

Why This Works

Step 1: Normalize case

Using toLowerCase() makes sure the comparison ignores uppercase or lowercase differences.

Step 2: Sort characters

Splitting and sorting the characters puts letters in order so we can easily compare the two words.

Step 3: Compare sorted strings

If the sorted strings are exactly the same, it means both words have the same letters in the same amounts, so they are anagrams.

🔄

Alternative Approaches

Using character frequency count
javascript
function isAnagram(str1, str2) {
  if (str1.length !== str2.length) return false;
  const count = {};
  for (const char of str1.toLowerCase()) {
    count[char] = (count[char] || 0) + 1;
  }
  for (const char of str2.toLowerCase()) {
    if (!count[char]) return false;
    count[char]--;
  }
  return true;
}

console.log(isAnagram('listen', 'silent')); // true
This method counts letters instead of sorting, which can be faster for very long strings but is more complex to understand.
Using Map to count characters
javascript
function isAnagram(str1, str2) {
  if (str1.length !== str2.length) return false;
  const map = new Map();
  for (const char of str1.toLowerCase()) {
    map.set(char, (map.get(char) || 0) + 1);
  }
  for (const char of str2.toLowerCase()) {
    if (!map.has(char)) return false;
    map.set(char, map.get(char) - 1);
    if (map.get(char) < 0) return false;
  }
  return true;
}

console.log(isAnagram('Triangle', 'Integral')); // true
Using Map provides clearer key-value handling but is slightly more verbose.

Complexity: O(n log n) time, O(n) space

Time Complexity

Sorting the characters takes O(n log n) time where n is the length of the string, which dominates the runtime.

Space Complexity

Extra space is used to store the arrays of characters during splitting and sorting, which is O(n).

Which Approach is Fastest?

Counting characters with a frequency map can be faster (O(n)) than sorting, but sorting is simpler and good for short strings.

ApproachTimeSpaceBest For
Sorting and comparingO(n log n)O(n)Simple and short strings
Frequency count with objectO(n)O(n)Long strings, better performance
Frequency count with MapO(n)O(n)Clear key-value handling
💡
Always convert strings to lowercase before comparing to ignore case differences.
⚠️
Forgetting to normalize case or ignoring spaces and punctuation can cause wrong results.