Zerium
Zerium

Reputation: 17333

How to match 0 and an empty string, but not 0 and undefined, and not 0 and null, in JavaScript?

So basically, I want to have the program return true when an equality test is put with 0 and an empty string (""). Then, I could use the following without any error:

0 == ""; // true

But I don't want to match:

0 == null
0 == undefined
"" == null
"" == undefined

I want them all to return false. How is this possible? I don't think there's an operator for this, so is there a way I can change their values to make this work somehow?

Upvotes: 0

Views: 141

Answers (3)

LetterEh
LetterEh

Reputation: 26696

The answer is "not really".

You can't put them up against each other like that, and expect it to work.
Use || and use two statements, but use ===, instead of ==.

The double-operator will try to cast to different types.
The triple-operator requires them to be the same type.

0 == "" // true
0 === "" // false


(testValue === 0 || testValue === "") // will return false for undefined/null/NaN/false

Upvotes: 0

lupatus
lupatus

Reputation: 4248

function eq(value) {
    return (value === 0 || value === "");
}

Upvotes: 1

Chuck Norris
Chuck Norris

Reputation: 15190

function Equals(a,b) {

   if(a===b || (a===0 && b === "") || (a==="" && b === 0)) return true;
    return false;

}

You can look at jsfiddle example.

Upvotes: 1

Related Questions