ctaylor ctaylor - 4 years ago 145
Javascript Question

Check if a string is composed of all unique characters-- not equal to operator in JavaScript

I have written the following code to check if a string is composed of all unique characters

function isUnique(string) {
var charMap = {};
for(var i= 0; i < string.length; i++) {
if (charMap[string[i]] != null) {
charMap[string[i]] = 1;
return false;
} else {
charMap[string[i]] = 0;
}
}
return true;
}


This works when I run it, however, my linter is recommending I use "!==" rather than "!=" to compare to null.

if I change this line to
if (charMap[string[i]] !== null) {
, The code stops working and returns false regardless.

If I change this line to
if (charMap[string[i]]) {
(which I think should be the same), the function returns true regardless.

Can someone please give a plain text explanation of the differences between these three? I may be making a silly mistake in thinking they are similar so please bear with me.

Answer Source

There are two values in JavaScript which are very similar to each other: undefined and null.

undefined is the default state of all variables, including the value of unknown properties in an object.

var x;
console.log(x); // undefined

var obj = {
  a: 1
};
console.log(obj.b); // undefined

null is a value you can assign to something. It's generally used to imply that a value is purposefully non-existent.

When doing a weak comparison against null (!= null), it's the equivalent of doing:

x !== null && x !== undefined

By changing your code to

if (charMap[string[i]] !== null) {

you're omitting the check for undefined, which is what you really wanted in the first place.

Next, you tried

if (charMap[string[i]]) {

This checks to see if the value is "truthy". Basically, it translates to:

x !== false && x !== null && x !== undefined && x !== '' && x !== 0

That last clause is what's catching you. You initialize the value to 0 to start with but your code will never catch that.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download