OneBite.Dev - Coding blog in a bite size

Determine if all string has unique characters in Javascript

Determine if a string has all unique characters, you can use a Set in JavaScript. See case sensitive and insensitive version.

If you want to determine if a string has all unique characters, you can use a Set in JavaScript. A Set object lets you store unique values: when a value is added to a Set, it does not add it if the value is already in the Set. We can use this feature to easily check if all characters in a string are unique.

Code sample solution

Here’s a function that does this:

function isUnique(str) {
  return new Set(str).size === str.length;

console.log(isUnique("Hello"));  // Prints: false
console.log(isUnique("World"));  // Prints: true


In this function, new Set(str) creates a set from the characters in the string. The size property of the set is the number of unique characters in the string. If this is equal to the length of the string, then all characters in the string are unique, and the function returns true. If not, the function returns false.

Time Complexity Info

The time complexity of this function is O(n), where n is the length of the string. This is because creating a Set from a string requires iterating over the string once. Therefore, this function is quite efficient.

Warning: Please note that this function is case-sensitive.

Case insensitive version

If you want to make it case-insensitive (so that, for example, ‘A’ and ‘a’ are considered the same character), you can convert the string to lower case or upper case before creating the Set:

function isUnique(str) {
  return new Set(str.toLowerCase()).size === str.length;
← Chunking array buy n numb...
Check if two strings is a... →