Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

Yes

I hate the 15 char limit.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top