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 short, one line code, but is this legal, and cross browser valid? I mean, jslint says it has errors. Should I use it without concerns?
We can also write multiple conditions inside a single if statement with the help of the logical operators && and | | . The && operators will evaluate if one condition AND another is true. Both must be true before the code in the code block will execute.
You can use the logical AND (&&) and logical OR (||) operators to specify multiple conditions in an if statement. When using logical AND (&&), all conditions have to be met for the if block to run.
The logical AND (&&) operator and if...else statements in JavaScript. In the logical AND ( && ) operator, if both conditions are true , then the if block will be executed. If one or both of the conditions are false , then the else block will be executed.
Using either “&&” or “||” i.e. logical AND or logical OR operator or combination of can achieve 3 conditions in if statement JavaScript.
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.
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With