Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You need to use the <a href="https://stackoverflow.com/questions/359494/javascript-vs-does-it-matter-which-equal-operator-i-us">identity operator <code>===</code>, not the equality operator <code>==</code></a>. With this change, your <a href="http://jsfiddle.net/A89Qj/2/" rel="nofollow noreferrer">code works as expected</a>:</p> <pre><code>alert(a===null); // true alert(a===undefined); // false alert(b===null); // false alert(b===undefined); // true </code></pre> <p>The reason the equality operator fails in this case is because it attempts to do a type conversion. <code>undefined</code> is of type <code>undefined</code>, and <code>null</code> is of type <code>object</code>; in attempting to compare the two, Javascript converts both to <code>false</code>, which is why it ends up considering them equal. On the other hand, the identity operator doesn't do a type conversion, and requires the types to be equal to conclude equality.</p> <p><strong>Edit</strong> <em>Thanks to @user1600680 for pointing out, the above isn't quite correct; the ECMAScript specification defines the null-to-undefined as special case, and equal. There's no intermediate conversion to <code>false</code>.</em></p> <p><hr/> A simpler example of type conversion is number-to-string:</p> <pre><code>console.log(5 == "5"); // true console.log(5 === "5"); // false </code></pre> <hr/> <p>The above answer has a good quote from Douglas Crockford's <em>Javascript: The Good Parts</em>:</p> <blockquote> <p>[The "==" operator does] the right thing when the operands are of the same type, but if they are of different types, they attempt to coerce the values. the rules by which they do that are complicated and unmemorable.</p> </blockquote> <p>If you don't believe that the rules are <em>complicated and unmemorable</em>, a <a href="http://jibbering.com/faq/notes/type-conversion/" rel="nofollow noreferrer">quick look at those rules</a> will disabuse you of that notion.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload