Last week I finished Douglas Crockford's series "The JavaScript Programming Language", which is a fantastic series that I highly recommend. I thought that I would share with you a few interesting tidbits that I had seen in other people's code but had not quite grasped until now.
Type coercion
An interesting aspect of JavaScript is that the equal operator (==) will do type coercion. Example: "10" == 10 will evaluate to true because JavaScript will convert both types to an int before comparing the two values. Sometimes this is good (I guess), most times it is not. Well, JavaScript answers with a second type of equal operator: ===. In the same scenario "10" === 10 will evaluate to false because no type coercion has occurred.
Guard operator
We are all familiar with the logical-and operator (&&). What I wasn't familiar with is JavaScript's interpretation of the && operator as a guard operator. For instance,
this:
if (A) {
return A.name;
}
else {
return A;
}
can be written like this:
return A && A.name;
The name will only be returned if A has a value, think of A "guard'-ing against a null exception.
Default operator
The default operator is a great way to specify, defaults. For example,
foo = A || 20;
if A has a value then A will be returned else 20 will be returned as the default value. Very slick!
Once you begin thinking in this way you'll start writing less "if" statements and more concise, easier to read JavaScript.