Wednesday, October 28, 2009

Using the "in" operator in conditionals

Most of us are familiar with the for..in loop construct:

for (var i in object) {
   /* some iterative action here */
}

Less well-known is the use of "in" as an operator to test if a named property exists on an object:

>>> var x = {foo:1, bar:2, baz:'cat'};

>>> ('foo' in x)
true

>>> ('bar' in x)
true

>>> ('qux' in x)
false
This works on methods, too:
>>> ('toString' in x)
true

It's particularly neato for testing the existence of properties with values that could be interpreted as false:

>>> var x = {foo:null, bar:false, baz:0};

>>> (x.foo)
null

>>> ('foo' in x);
true

>>> (x.bar)
false

>>> ('bar' in x)
true

Friday, October 09, 2009

IE conditional comment gotcha

Here's one for the books:

<!-- [if IE]>

<p>Some IE-specific stuff here</p>

<![endif] -->

This will be ignored by IE. Why?

Because IE doesn't like the whitespace between the comment delimiters and square brackets. Here's the correct way:

<!--[if IE]>

<p>Some IE-specific stuff here</p>

<![endif]-->

Note the difference:

<!-- [if IE]> (bad)
<!--[if IE]>  (good)