views:

40

answers:

2

The if(variable) clause in the following constructs checks if list/array is not null/undefined, to avoid an exception:

if (list)
    for (var k in list) {
       ...

if (array)
    for (var i = array.length; i >= 0; i--) {
        ...

But JS syntax allows expressions like

null || []
undefined || {}

So I can make code shorter by one line and still check the array/object:

for (var k in obj || {}) {
    ...

for (var i = (array || {}).length; i >= 0; i--) {
    ...

The question essentially is: does null/undefined || []/{} expression return the latter in all browsers?

edit: found out that curly brackets are better for for (var k in list || {}) iteration, because an array (square brackets) cause an iteration and an exception is thrown.

+3  A: 

Yes, null, undefined, 0, "", will all resolve to false, when treated as a boolean (which the || operator does), and so, all browser will use the latter. This behavior is perfectly safe.

David Hedlund
+2  A: 

Yes

I hate the 15 char limit.

Marius
+1 for 15 char limit. altho it's not very related to the question, i agree emphatically, at least when it comes to comments
David Hedlund
yesssssssssssss
shylent