(null! = someVariable) OR (someVariable! = null)

What is the difference between (null! = SomeVariable) and (someVariable! = Null)? I saw a lot of people who first used โ€œzeroโ€ in comparison. Which one is better than the other and why?

+2
javascript
source share
4 answers

They are equivalent.

However, the first one will result in an invalid assignment error if you make a mistake != As = . Some people like this, as it's pretty easy to type = instead of == , although the former is not always random.

You can see the exact specification rules regarding the == operator on Annotated ES5 .

+3
source share

They evaluate the same thing, but it is preferable to choose (someVariable != null) , because the (someVariable != null) condition is another way. It deals with readability.

+3
source share

The first may be better. someVariable is actually a function with a very long list of arguments. At first glance, your intention would be easier to see. Otherwise, I always use the second one.

0
source share

Suppose you want:

 if (number == 42) { /* ... */ } // This checks if "number" is equal to 42 // The if-condition is true only if "number" is equal to 42 

Now imagine that you forget that there should be a double = , and you just write only one = :

 if (number = 42) { /* ... */ } // This assigns 42 to "number" // The if-condition is always true 

Such errors are quite common and difficult to detect in programming languages โ€‹โ€‹that allow you to assign variables in conditional expressions.

Now consider changing the order of your state:

 if (42 == number) { /* ... */ } // This checks if "number" is equal to 42 // The if-condition is true only if "number" is equal to 42 

The behavior of 42 == number exactly matches the behavior of number == 42 .

However, if you make the same mistake mentioned above (you forget that there should be a double = , and instead you just write one = ), the behavior will no longer be like this:

 if (42 = number) { /* ... */ } // This produces an error 

Therefore, some people prefer to change the order of their conditions, as this makes a common mistake much easier to detect. Such โ€œreverseโ€ conditions are known as the Yoda Conditions .

In programming languages โ€‹โ€‹that do not allow you to assign variables to conditional expressions (such as Python or Swift), there are no advantages to using Yoda conditions, and they are usually not recommended to use them. In other languages โ€‹โ€‹(like JavaScript or PHP), Yoda conditions can be very useful. However, in the end, it still depends heavily on your personal preferences or any coding standards that your project requires.

Wordpress and Symfony are two popular open source projects where Yoda terms are part of the coding standards.

0
source share

All Articles