سؤال

Common practice when checking whether a variable is undefined in JavaScript is as follows:

var isUndefined=(typeof variableName==="undefined");


I've recently come across the use of two exclamation symbols to determine the same logic:

var isUndefined=!!variableName;



Is it safe to use these methods interchangeably?
Are both equally compatible across browsers?
Is there any reason why one shouldn't use the "!!" method? (It seems more concise and easy to read)

هل كانت مفيدة؟

المحلول

Is it safe to use these methods interchangeably?

No. Details below, but they're not interchangeable even if you remove one of the ! from your second example (with two of them, it will be true for undefined, which isn't what you seem to want from the name of the variable you're assigning to). But that's not the only issue.

Are both equally compatible across browsers?

Yes. Each of them works reliably across browsers. But see above: They reliably don't do the same thing.

Is there any reason why one shouldn't use the "!!" method?

Yes, ! (again, not !!) gives the same result for 0, NaN, null, "", and false as it does for undefined.

Details:

When you do

var isUndefined = typeof variableName==="undefined";

(the () are unnecessary), you're doing a very specific test for undefined. It will only be true for undefined.

In contrast, when you do

var isUndefined = !variableName;

you're not testing for undefined, you're testing for any falsey value. The falsey values are the ones I listed earlier (0, NaN, null, "", false, and undefined). The result will be true for any of them.

Now, if you're expecting (for instance) to get a non-null object reference or undefined, the ! test is just fine. But if you really need to know whether something is undefined, specifically, you want the typeof test.

Also, as Felix Kling pointed out in a comment on the question, the ! test will throw a ReferenceError if the variable isn't defined at all (as opposed to being defined but having the value undefined), because it tries to read the value of the variable. The typeof test is safe if you're not sure whether the variable exists at all, because it doesn't try to read its value.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top