culebrón
culebrón

Reputation: 36473

Will (variable or {}) work crossbrowser in Javascript?

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.

Upvotes: 1

Views: 91

Answers (2)

Marius
Marius

Reputation: 58941

Yes

I hate the 15 char limit.

Upvotes: 2

David Hedlund
David Hedlund

Reputation: 129802

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.

Upvotes: 3

Related Questions