Two strings are anagrams of each other if they contain exactly the same letters in the same quantities, just rearranged — for example, “listen” and “silent”. This is a very common interview question because it can be solved with two meaningfully different techniques: sorting, and frequency counting.

JavaScript Program to Check Anagram Strings (Sorting Approach)

function isAnagram(str1, str2) {
  const normalize = (str) =>
    str.toLowerCase().replace(/[^a-z]/g, "").split("").sort().join("");

  return normalize(str1) === normalize(str2);
}

console.log(isAnagram("listen", "silent"));
console.log(isAnagram("hello", "world"));

Output:

true
false


JavaScript Program to Check Anagram Strings (Frequency Counting)

Sorting both strings works but costs O(n log n). A frequency-count comparison does the same check in O(n) by counting how many times each letter appears in both strings.

function isAnagramFast(str1, str2) {
  const clean1 = str1.toLowerCase().replace(/[^a-z]/g, "");
  const clean2 = str2.toLowerCase().replace(/[^a-z]/g, "");

  if (clean1.length !== clean2.length) return false;

  const counts = {};
  for (const char of clean1) counts[char] = (counts[char] || 0) + 1;
  for (const char of clean2) {
    if (!counts[char]) return false;
    counts[char]--;
  }

  return true;
}

console.log(isAnagramFast("listen", "silent"));

Output:

true

For short strings the difference between O(n log n) and O(n) barely matters, but the frequency-count version is the better habit to build — it scales cleanly and is the technique interviewers usually expect once you’ve mentioned the sorting approach as a first pass.