Ad space (banner)
🟨JavaScript Lessons
Lesson 65 / 69

Checking for an Anagram

In this lesson you'll learn how to check whether two words are anagrams (related by rearranging letters), so you can practice this kind of comparison. This is for people searching "JavaScript anagram check" who landed here.

An anagram is a different word that can be made by rearranging the same letters (for example: listen and silent). You can check this by rearranging the letters of both strings and comparing whether they match. This relies on the property that if the type and count of characters in two strings are exactly the same, they're anagrams of each other regardless of the order they're arranged in.

The sample code, inside a function called normalize, uses the chain .toLowerCase().split("").sort().join("") to unify uppercase and lowercase, break the string apart into individual characters, sort them alphabetically, and join them back into a single string. If the two "normalized" strings match, they're anagrams.

A common beginner stumbling block is that, if you want to compare without distinguishing uppercase from lowercase, you need to unify the formatting ahead of time with something like .toLowerCase(). If you compare without first unifying the formatting, words that really are anagrams can end up judged as different strings.

This is a basic technique you can use when you want to compare strings while ignoring their character order, and it can also be applied to things like a simple cipher-breaking game or a puzzle app. It looks like a simple word game, but it's a useful subject for hands-on practice with string comparison.

JavaScript
OUTPUT

💡 Anything passed to console.log() appears in the output below.

Ad space (banner)
Ad space (in-article)