EDIT: Modules are delayed to a further blog post :p
But before this, let's talk about something else as an appetizer.
Boolean(false) is truthy
Javascript shares the burden of C-Style truthy/falsy concept. These are non-boolean expressions that can be treated as a boolean value. It is both powerful and very dangerous, because (once again) it presumes the developer already knows everything about the language's subtleties.
So let's first list the falsy elements, all the rest being truthy: 0,false (of course), empty string: "" or '', null
Presented this way, it seems quite simple... though there are some quirks due to where and how you're going to take advantage of these evaluations.
For example, 0 evaluates to false, while '0' evaluates to true (non-empty string). This sounds easy once again, but can be tricky when you receive a variable value and just test it this way: if(myVar){...}. It can lead to very counter-intuitive tests...
var myVar=new Boolean(false);
if(myVar){
alert("true");
// Never use alert() in real applications, it blocks all javascript execution in all tabs of a browser until you close it.
}
This is one example of code where one should stop thinking in another language's logic (Java or C# for example). new Boolean(false) is an object, and an object is always truthy, ending up with an alert popup showing "true".Though if you replace if(myVar)... with if(myVar==true)... the test will end up as expected, with nothing happening.
This can be confusing... I agree, and it did confuse me. Until I heard about the === operator. In javascript, == was designed as a tolerant operator, which accepts 1=='1' as a true assertion. So in later versions of javascript (when war between Netscape and IE was raging a while ago), a new === operator was introduced for a comparison of references. This operator is the one you'd want to use in order to be sure that an object is the same as another.
Oh and by the way, this may not be the last of my posts about javascript... so I'm going to drop in some of the references I used, in order not to forget them, and leave you my dear only reader with something else to read ;).
a Blog post about Truthy falsy
The source of all javascript wisdom ;): Sir Crockford.

0 commentaires:
Enregistrer un commentaire