Skip to content Skip to sidebar Skip to footer

Javascript: || Instead Of If Statement - Is This Legal And Cross Browser Valid?

It seems that: if (typeof a == 'undefined') { a = 0; } and (typeof a != 'undefined') || (a = 0) has the same effect in Javascript. I really like the second one because it is

Solution 1:

IMHO || (a = 0) is way too similar to || (a == 0) and thus confusing. One day overzealous developer will just "fix it", changing the meaning of your code. And every other developer will have to sit for a while to figure out whether this was your intent or just a simple bug.

And this is in fact what JSLint is trying to say:

Expected a conditional expression and instead saw an assignment.

I avoid using confusing constructs as they hurt readability. a = a || 0; is way more recognizable and similar in meaning.

Solution 2:

Why not something more simple, like:

a = a || 0;

or

a = a ? a : 0;

In both of these cases, you can also clearly see that something is being assigned to a, right at the start of the line, without resorting to reading the whole thing, and figuring out if there are any game-changing function-calls happening on either the left or right side... or figuring out what both sides do, in general, to decide how many potential program-wide changes there might be.

If you need to include the whole type-check, it's still not that large.

a = (typeof a !== "undefined") ? a : 0;  // [parentheses are there for clarity]

Solution 3:

is this legal, and cross browser valid?

Yes, it will work in all EcmaScript engines. However, it is very uncommon to (ab)use short-circuit-evaluation as an if-statement.

I mean, jslint says it has errors. Should I use it without concerns?

No, JsLint is right. It is unusual and confusing, at least to other developers. It looks too much like an OR-condition - yet is has no "body". And if you do assignments, the variable is expected to be on the beginning of the statement, not inside some expression.

I really like the second one because it is short, one line code

Then use

if (typeof a == 'undefined') a = 0;

Solution 4:

You can use:

a = typeof(a) !== "undefined" ? a : 0; 

Solution 5:

Stylistically, setting default values like a || a=default is a common idiom on entry into a function, because javascript doesn't enforce the number of arguments.

Readability will be compromised if this construct is used in other circumstances, where you really mean if/else.

Performance used to vary between the different styles, but in a quick test today if/else and logical operators were the same speed, but ternary operation was slower.

Post a Comment for "Javascript: || Instead Of If Statement - Is This Legal And Cross Browser Valid?"