(null != someVariable) OR (someVariable != null) - javascript

What is the difference between (null != someVariable) and (someVariable != null)? I have seen a lot of people using 'null' first in the comparison. Which one is better than the other and why?

They're equivalent.
However, the first one will cause an invalid assignment error if you mistype != as =. Some people like this as it's rather easy to type = instead of ==, although the former isn't always an accident.
You can see the precise rules of the specification with regard to the == operator on the Annotated ES5.

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

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

Consider you want this :
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 you forget there should be a double = and you just write a single = instead :
if (number = 42) { /* ... */ }
// This assigns 42 to "number"
// The if-condition is always true
Such errors are pretty common and can be hard to detect in programming languages that allow variable assignments within conditionals.
Now, consider reversing the order of your condition :
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 is exactly the same as the behavior of number == 42.
However, if make the same mistake mentioned hereabove (you forget there should be a double = and you just write a single = instead), the behavior is no longer the same :
if (42 = number) { /* ... */ }
// This produces an error
Therefore, some people prefer to reverse the order of their conditions, as it makes a common error much easier to detect. Such "reversed" conditions are known as Yoda conditions.
In programming languages that do not allow variable assignments within conditionals (eg. Python or Swift), there is no advantage whatsover to using Yoda conditions, and it's typically discouraged to use them. In other languages (eg. JavaScript or PHP), Yoda conditions can be very useful. However, in the end, it's still largely a matter of your personal preference or whatever coding standards your project require.
Wordpress & Symfony are two popular open source projects where Yoda conditions are part of the coding standards.

Related

Javascript comparisons == null alternatives

In JavaScript code I want to replace the double-equals structure of the following if-statement:
if( name == null ) {
//do stuff
}
The double equals fail for the jshint rule "eqeqeq", where it's recommended to replace double equals with triple equals. For a moment, let's imagine the above code changed from == null to === null like this:
if( name === null ) {
//do stuff
}
This would work for a variable explicitly defined having the value null, but unfortunately would fail for any unset variables like this.
var a = null; // works correctly
var b; // will fail in comparison
Previously when the triple-equals rule was important to me I would do the following
if( name === null ||| typeof(name) === 'undefined' )
but I find this extremely bloated.
The best alternative I can come up with now is to use the nature of the if-statement and let it evaluate to a false-ish expression like here where I negate the expression and simply remove the == null part:
if( !name ) {
//do stuff
}
For me, this is much simpler, easy to read, and completely avoids explicit equals comparison. However, I am uncertain if there are any edge causes I am missing out here?
So the question is, can I generally replace == null with the negated expression if statements? If so, what are the pitfalls and exceptions where it wouldn't work? Does it work for general array items, strings, object properties?
My criteria for picking a solution will be
clean code
easy to read and quickly understand
validates jshint rules
works in modern browsers (as of writing January 2015)
I am aware of other slightly related questions for discussing difference in the equality operators == vs ===, but this is merely for a discussion of the evaluation compared to null-ish inside the if-statement.
So the question is, can I generally replace == null with the negated expression if statements?
Probably not universally, no, but perhaps in some places.
If so, what are the pitfalls and exceptions where it wouldn't work? Does it work for general array items, strings, object properties?
The !value check will be true for all of the falsey values, not just null and undefined. The full list is: null, undefined, 0, "", NaN, and of course, false.
So if you have name = "" then
if (!name) {
// ...
}
...will evaluate true and go into the block, where your previous
if (name == null) {
// ...
}
...would not. So just doing it everywhere is likely to introduce problems.
But for situations where you know that you do want to branch on any falsey value, the !value thing is very handy. For instance, if a variable is meant to be undefined (or null) or an object reference, I'll use if (!obj) to test that, because any falsey value is good enough for me there.
If you want to keep using JSHint's === rule, you could give yourself a utility function:
function isNullish(value) {
return value === null || typeof value === "undefined";
}
The overhead of a function call is nothing to be remotely worried about (more), and any decent JavaScript engine will inline it anyway if it's in a hotspot.

Using Logical AND in Javascript Variable Declarations

I am interested in the practical application of declaring variables using && like this:
var x = undefined && 4;
// Evaluate to the first falsey value
// or else the last value.
eval(x);
// undefined
I understand how the value is evaluated (see this SO answer). I also understand its sister || (see here for a great description) and why it would be useful to declare a variable with the following expression:
// Some other variable
var y;
var x = y || 4;
// Evaluate to the first truthy value
// or else the last value.
Practically: Use the first value unless that first value is falsey; if so, use the last value. We can demonstrate this characteristic of || in the browser console:
> null || 4
4
> 4 || null
4
> null || undefined
undefined
> undefined || null
null
> true || 4
true
> 4 || true
4
As for &&:
> null && 4
null
> 4 && null
null
> null && undefined
null
> undefined && null
undefined
> true && 4
4
> 4 && true
true
Should we take this to mean: Use the first value unless that first value is truthy; if so, use the last value?
I'm interested in using coding shortcuts to minimize the use of conditional statements, and I wonder if I might be able to use this one somehow.
I found an example of this coding method in line 472 of the jQuery core source:
scripts = !keepScripts && [];
So the question is this: Can anyone describe a good context for using && in a javascript variable declaration? Do you consider it to be bad practice?
Thanks!
In general, you should only only use "shortcuts" like this if it makes the code more readable for the typical JavaScript programmer than the alternative.
When thinking about what is more readable, and less surprising, consider that
var foo;
if(bar) {
foo=[];
}
and
var foo = bar && [];
are not the same. For instance, if bar is NaN, then foo will then be NaN in the later case, which might be a bit of a head-scratcher later on.
Since there are tools to optimize/minimize JavaScript, you should focus on readability of your code, which is not always the same thing as brevity.
Lets say you have several such repetitive initializations in a row, all dependent on different variables (so that they couldn't be wrapped into a single conditional), but following the same logical formula. In this case, once the reader had mentally parsed the meaning of the formula, they could quickly scan all the instances and see the differences between each one. In this case, instead of relying on a convention that most JavaScript programmers are familiar with (such as var foo = some_opt || {}), you are creating a localized convention, that the reader will have to learn just for this file. Even in this case, I'd advise some careful consideration, its probably not worth it.
I found one specific circumstance in which it can be useful to use && in the debugging process.
Let's say we have a variable x. Sometimes x has a value of null, and sometimes x is an Object with value {'foo':'bar'}. We want to write an expression that returns the value of x.foo if it exists.
However, we have to be careful. Calling a property of an object that does not exist can result in this:
> Uncaught TypeError: Cannot read property 'foo' of null
So we can write this:
x && x.foo
Which does the following:
If x is an Object and x.foo exists, give us the value of x.foo.
If x is an Object and x.foo doesn't exist, return undefined.
If x is null, return null.
As long as x has been mentioned somewhere (even if x is simply set to null or undefined), the expression should not break the code.
Actually, you should not regularly use && operator like Jquery does since it is always risky code. You may forget what you have done or you may not find a bug due to the this usage. I personally consider this as a bad practice. You may prefer to use, but code becomes unreadable. We, developers should think about understandability and readability of the code.
Well, it's a common idiom but maybe it makes your code less readable. So, my suggestion, keep it simple, even if it means a few more keystrokes.

Does order of operands in equality matter? (e.g. 1 == x vs x == 1)

So I'm trying out the Google Closure Compiler and I've noticed that it switches all my equality parameters so that the variables are always on the right side of the comparison.
So now instead of typeof XMLHttpRequest=="undefined" I have "undefined"==typeof XMLHttpRequest and I have if(null!==a) instead of if(a!==null), just as some examples.
I know they accomplish the same thing, but it's just not the style I'm used to. Is there some sort of benefit that you get for having these switched? I can't see how there would be.
Can someone explain to me why the Closure Compiler decides to do this? Is it just a preference of whoever wrote that part of Closure?
Edit: To clarify, people are telling me why it might be considered good coding practice. That's fine, but this is after compilation. Is there a performance benefit or is the Closure Compiler just trying to prove a point?
Commonly done in languages like C / C++ so you can't accidently do
if (a = null) {
// sets a to null and everyone is happy.
// but probably meant to check if a is null or not.
// via (a == null)
}
if (null = a) {
// won't compile
}
The compiler switches the order for a very simple reason: it compresses better with gzip. The compiler doesn't care a wit about improving comprehension or making it easier to edit. By switching the order common comparisons such as "if (x == null) ... if (y == null) ..." become "if (null == x) ... if (null == y) ..." Gzip finds "if (null ==" and is able to replace it with a single token. It isn't a big improvement, but it adds up in a large code base.
Yes, you can't assign to a constant, and == is easy to mistype (sometimes you may forget one, and use =).
For example, what's the difference between...
if (a == 1) { }
...and...
if (a = 1) { }
? The second one will always evaluate to true, not matter what the value of a.
If you flip the LHS and RHS, you can see the immediate benefit...
if (1 == a) { }
...will work as expected and...
if (1 = a) { }
...will fail, as you can't assign to a constant.
The reason I know is is done to prevent
if (x = 5) { }
If you reverse it to
if (5 = x) { }
You would get a compiler error.
But if you write it as
if (5 == x) { }
It will compile fine.
My brain parses
if( x < y )
slightly faster than
if( y > x )
probably because real axis is always oriented from left to right, thus making condition easier to visualize.
However, in java it is more practical to write
if( "string".equals(x) ) {...
as opposed to "more natural"
if( x.equals("string") ) {...
to eliminate any opportunity for NPE.
Just a cheap replacement of static analysis of particular case of common mistake/

Does it make sense to use === for string comparison in JavaScript?

While it's clear how using the === operator for e.g. numbers is useful (0, null and undefined all being falsy values, which can lead to confusion), I'm not sure if there are benefits to using === for string comparisons.
Some of my team mates use this operator for all comparisons, but does it really make sense? Is there at least some minor performance impact?
If you know the types are the same, then there's no difference in the algorithm between == and ===.
That said, when I see ==, I assume that I'm using it for its type coercion, which makes me stop and analyze the code.
When I see === I know that there's no coercion intended, so I don't need to give it a second thought.
In other words, I only use == if I intend for there to be some sort of type coercion.
It is considered good practice to always use === for comparisons in JavaScript. Since JavaScript is a dynamic language, it is possible that what you think are two strings could be variables with different types.
Consider the following:
var a = "2", b = 2;
a == b // true
a === b // false
The only way to guarantee a false result in this case would be to use === when comparing the two values.

In Javascript, is it not recommended to use ==, and how to use ===? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Javascript === vs == : Does it matter which “equal” operator I use?
In Douglas Crockford's book Javascript: The Good Parts, it is recommended to not use == at all, due to hard to memorized rules. Do advanced or seasoned Javascript programmers really not use == or !=?
If so, then I guess we will be using === and !==, but then how do we use them effectively? Is the most common case comparing a string with number, so we can always do
if (Number(s) == 3) { ... } // s is a string
Can Number(s) work in most browsers? And what are the other common cases to use with ===?
The problem with == is that it uses type-coercion which can have unexpected results.
You nearly always want === or !==. You can explicitly change the types as appropriate. In your example it would be easier to write "3" as a string instead of converting the string to a number.
Never say never, but indeed, in most cases it is best to use the more strict === and !== operators, because they compare the value as well as the type.
Comparing '68' to 68 is not a problem, if it matches, it is probably what you meant. The big risk in not doing so lies especially in 'empty values'. Empty strings may be evaluated as false, as may 0 and 0.0. To prevent hard to find errors, it is best to do a strict type comparison as well.
If you want something to be true or false, it should be true or false and not any other value. Even in cases where these other types would be allowed, it may be better to explicitly convert it to the type you're comparing with, just for the sake of readability, maintanability and clarity. You are in that case making clear that you know the value can be of another type and that it is allowed so. With just using the less strict operator, no one can tell if you just forgot or made a deliberate choice.
So yes, I'd say it's a best practise to always use the strict operators, although there will always be exceptions.
=== is 'exactly equal to' where == is not exact.
For example,
'' == false // true
0 == false // true
false == false // true
'' === false // false
0 === false // false
false === false // true
== will return true for 'falsy' or 'truthy' values. Read this for more information.
A lot of developers will use ===. It does not hurt to use === solely. But in some cases === is not necessary. Crockford suggests a lot of things in his book. Some people follow his word to the T. Others, myself included, take it all with a grain of salt. He has some good points, but a lot of it is preference.
You should make sure you know exactly what == and === do. And with that information you can decide how to use them, and when.
== operator compares two operands values and returns a Boolean value.
=== This is the strict equal operator and only returns true if both the operands are equal and of the same type.
Example:
(2 == '2') //return true
(2 === '2') //return false

Categories

Resources