Javascript Lesson 3 - Truthy

by ironicmuffin

HTML

<html>
<head>
    <link href="http://code.jquery.com/ui/1.9.2/themes/base/jquery-ui.css" rel="stylesheet" />
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.8.3.js"></script>
        <script type="text/javascript" src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
</head>

<body>


    <h1>Javascript Lesson 3 - Truthy</h1>
    
    <p id="message"></p>

</body>
</html>

CSS

h1 {
font-weight: bold;
font-size: 18px;
 margin: 5px;   
}
p {
 margin: 5px;   
}

JavaScript

/*
JavaScript has two sets of equality operators: === and !==, and their evil twins == and !=. The good ones work the way you would expect. If the two operands are of the same type and have the same value, then === produces true and !== produces false. The evil twins do 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. These are some of the interesting cases:
*/
var $msg = $('#message');
$msg.html($msg.html() + "'' == '0': " + ('' == '0').toString()); 
$msg.html($msg.html() + "<br />0 == '' : " + (0 == '').toString()); 
$msg.html($msg.html() + "<br />0 == '0' : " + (0 == '0').toString()); 

$msg.html($msg.html() + "<br /><br />false == 'false' : " + (false == 'false').toString()); 
$msg.html($msg.html() + "<br />false == '0' : " + (false == '0').toString()); 

$msg.html($msg.html() + "<br /><br />false == undefined' : " + (false == undefined).toString()); 
$msg.html($msg.html() + "<br />false == null : " + (false == null).toString()); 
$msg.html($msg.html() + "<br />null == undefined : " + (null == undefined).toString()); 

$msg.html($msg.html() + "<br /><br />' \t\r\n ' == 0 : " + (' \t\r\n ' == 0).toString()); 
     // true

/*
The lack of transitivity is alarming. My advice is to never use the evil twins. Instead, always use === and !==. All of the comparisons just shown produce false with the === operator.
*/