Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: || instead of IF statement - is this legal and cross browser valid?

Tags:

javascript

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?

like image 452
Tamás Pap Avatar asked Sep 28 '12 07:09

Tamás Pap


People also ask

Can you put two conditions in an if statement JavaScript?

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.

How do you write two conditions in JavaScript?

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.

Can I use && in if statement in JavaScript?

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.

Can IF statement have 3 conditions JavaScript?

Using either “&&” or “||” i.e. logical AND or logical OR operator or combination of can achieve 3 conditions in if statement JavaScript.


2 Answers

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.

like image 79
Tomasz Nurkiewicz Avatar answered Oct 16 '22 06:10

Tomasz Nurkiewicz


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] 
like image 42
Norguard Avatar answered Oct 16 '22 06:10

Norguard