Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: Order of operands in comparison operator [duplicate]

Is there a specific reason why I have seen many people writing

if(1 === a) {...}

instead of

if(a === 1) {...}

I had given an answer in which I wrote something like Array === obj.constructor which is when someone asked me that he has often seen people writing like this instead of obj.constructor === Array.

So does it really matter which way I use?

like image 679
shinobi Avatar asked Jun 26 '16 06:06

shinobi


People also ask

Does || or && have higher precedence?

The logical-AND operator ( && ) has higher precedence than the logical-OR operator ( || ), so q && r is grouped as an operand. Since the logical operators guarantee evaluation of operands from left to right, q && r is evaluated before s-- .

What is the order of precedence in JavaScript?

Operators are first grouped by precedence, and then, for adjacent operators that have the same precedence, by associativity. So, when mixing division and exponentiation, the exponentiation always comes before the division.

Do all comparison operators have the same precedence?

Precedence RulesAll comparison operators have equal precedence, and all have greater precedence than the logical and bitwise operators, but lower precedence than the arithmetic and concatenation operators.

Which operator has highest precedence in JavaScript?

The grouping operator is assigned the highest level of precedence.


1 Answers

It's yoda conditions:

Yoda conditions are so named because the literal value of the condition comes first while the variable comes second. For example, the following is a Yoda condition:

if ("red" === color) {
    // ...
}

This is called a Yoda condition because it reads as, “red is the color”, similar to the way the Star Wars character Yoda speaks. Compare to the other way of arranging the operands:

if (color === "red") {
    // ...
}

This typically reads, “color is red”, which is arguably a more natural way to describe the comparison.

Proponents of Yoda conditions highlight that it is impossible to mistakenly use = instead of == because you cannot assign to a literal value. Doing so will cause a syntax error and you will be informed of the mistake early on. This practice was therefore very common in early programming where tools were not yet available.

Opponents of Yoda conditions point out that tooling has made us better programmers because tools will catch the mistaken use of = instead of == (ESLint will catch this for you). Therefore, they argue, the utility of the pattern doesn’t outweigh the readability hit the code takes while using Yoda conditions.

like image 62
Anthony Astige Avatar answered Oct 14 '22 16:10

Anthony Astige