I recently read a post in [Bertrand Le Roy's blog] titled [A nice and compact way to coerce to Boolean in JavaScript]. Having used JavaScript extensively for the past few years, I knew from the title what the post would be about - the lovely double negation: !!somevariable - the shortest way to say "parse boolean" in JavaScript. While the trick was not new to me, the blog post did give me the idea to share a couple of similar tips:
Type Conversions
A compact way to convert to integer: somevariable - 0
A compact way to convert to string: somevariable + ''
None of these may be very readable at first, but I found them very easy to get used to. They certainly are short to write, which counts when writing web controls. And frankly, I never was a big fan of "parseInt".
Note also that
parseInt(somevariable) and
somevariable-0 are not equivalent. For example,
parseInt(true) evaluates to
NaN, while
true-0 evaluates to
1. I prefer the latter.
I first learned these three tricks from David Flanagan's [JavaScript: The Definitive Guide], a terrific book.
Here are a couple more tricks I learned from that book (or was it somewhere else?):
Undefined vs null and === vs ==
When you just a declare a variable
foo, but you do not assign a value to it, what is its value? You may think it is
null, because
foo==null evaluates to
true, but this is not exactly correct. The value is actually undefined - or unassigned, if you prefer. You can prove this by using the identity operator,
===:
var foo;
alert(foo == null); // true
alert(foo === null); // false
var o = new Object();
alert(o.bar == null); // true
alert(o.bar === null); // false
alert(o.bar == foo); // true
alert(o.bar === foo); // true
alert(foo === void 0); // true
The last line uses the operator void, another recluse. Its purpose is to discard the value of its operand and return an undefined value instead. If you are writing code and need an undefined value, you should do what cool kids do and use void 0, instead of an unassigned dummy variable or something else lame.
So: undefined value is not null value, which can be proven using the identity operator, which is not the equality operator. But will you actually need this any time soon? Probably not. Identity operator, undefined value, and void operator are used more often in examples like this one than in actual code. But I did occasionally have a need for them, so it pays to keep them in mind. Also they're fun to blog about.
for/in Loop
In contrast, for/in loop is very important in JavaScript. It enables looping through the properties of an object. This is indispensable in some cases - for example when you need to examine an unknown object:
for (var propertyName in myObject)
{
alert('Property ' + propertyName + ' has value: ' + myObject[propertyName]);
}