It seems that:
if (typeof a == \'undefined\') {
a = 0;
}
and
(typeof a != \'undefined\') || (a = 0)
h
May I ask why you prefer one line of code?
As a human, I prefer readable code. My machine prefers short and fast code (easy to load and execute).
Today minifiers like UglifyJS know how to shorten code, so you can have both and you don't need to worry about this level of detail. I gave your code to UglifyJS and here is the output:
typeof a=="undefined"&&(a=0)
You can try it out here:
http://marijnhaverbeke.nl/uglifyjs
[Update] My personal preference (again with readability in mind) is to use if when there are choices, and || for fallbacks. Your specific example seems to be a fallback (if a doesn't exist or is undefined, then assign to a the value 0), so I'd use ||. As I said in a comment, (var a=0) would make more sense to me in cases where the variable a hasn't been declared yet (I don't know your context).
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;
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.
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.