Using Logical AND in Javascript Variable Declarations - javascript

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.

Related

Purpose of redundant conditions in if-then clause with && (and) operator?

I don't understand the following if-then-else clause, which I found in a piece of code I'm working on.
if (prefstocking && prefstocking >0) {
...
} else {
...
}
Why does the variable prefstocking appear on both sides of the logical operator &&? I thought using the logical operator && meant using both of them, like this: if (x && y = 1) makes sense to me, meaning "if x equals 1 and y equals 1", but what is the meaning of using the same value twice?
Written in plain English, this test reads:
if prefstocking is truthy and its value is greater than 0
however, because most values are truthy, the former check is unnecessary. Any case which fails the first condition would also fail the second. I see a lot of developers write these kind of checks to be extra-sure, but it tells me that they simply aren't thinking about what they're doing.
The first part if (prefstocking && ...) checks the var prefstocking for false, null, undefined, 0, NaN, and the empty string.
These are all called "falsy" values.
If prefstocking is "falsy" then it isn't greater than zero and doesn't need to check that.
Another answer goes into some detail about truthy v. falsy in javascript.
In this case it makes no difference if the test is if (prefstocking > 0) because that will always evaluate to the same result as the original, but the principal is often useful, especially to avoid dereferencing a null or undefined object.
var obj1 = someFunction('stuff', 9); // assume it returns an object
var obj2 = getNullObj(); // assume it always returns null
// this is OK if an object is always returned from the someFunction(...) call
if (obj1.hasData()) { }
// this causes an error when trying to call the .hasData() method on a null or undefined object
if (obj2.hasData()) { }
But, because the logical and && and the or || operators short-circuit, testing like this is safe:
if (obj2 && obj2.hasData()) { }
If the first part is false (falsy) it won't try to evaluate the second part because the logical truth is already know - the whole statement is false if the first part of an and is false. This means .hasData() will never get called if obj2 is null or undefined.
If an object is defined but does not have a .hasData() function then this will still cause an error. Defending against that could look like
if (obj2 && obj2.hasData && obj2.hasData()) { }
// ...or...
if (obj2 && typeof obj2.hasData === 'function' && obj2.hasData()) { }
Short-circuiting allows you to check and avoid failure cases, but checking every possible failure could make your code unreadable and perform poorly; use your judgment.
Others are correct in pointing out that the way to read this is (prefstocking) && (prefstocking > 0). The first condition checks whether prefstocking is truthy. The second condition makes sure it's greater than 0. Now, as to why bother doing that? Here I disagree with the other answers.
There are situations in programming where we might use redundant conditions in an if then clause because of efficiency. In this situation, mathematically speaking the first condition is redundant. That is, if the second condition is true, then the first condition is also true. However, order matters. An if an interpreter checks the first condition and finds it false, followed by an && (and), then it doesn't need to test further. And it probably won't test the second condition (see comments below: according to ECMAScript standard, it definitely won't test the second condition). This could be useful if it is less computationally expensive to check the first condition, such as first ruling out null cases. The specifics of whether it's actually more efficient are hard to quantify with JavaScript because the internals are often not specified and each JS interpreter works in its own way.
Also, an expression of the form if (x && y == 1) would be interpreted as "if x is truthy and if y equals 1". You have misunderstood the order of operations. Both sides of the && make separate conditions. They don't combine into one condition like the might in English. This expression certainly does not mean "if x and y equal 1". Make sure you have understood that.

Best practice of checking if variable is undefined

I was having some issues in my conditions concerning undefined variables. What is, to sum it up, the best way to check if a variable is undefined?
I was mainly struggling with
x === undefined
and
typeof x === 'undefined'
You can use both ways to check if the value is undefined. However, there are little nuances you need to be aware of.
The first approach uses strict comparison === operator to compare against undefined type:
var x;
// ...
x === undefined; // true
This will work as expected only if the variable is declared but not defined, i.e. has undefined value, meaning that you have var x somewhere in your code, but the it has never been assigned a value. So it's undefined by definition.
But if variable is not declared with var keyword above code will throw reference error:
x === undefined // ReferenceError: x is not defined
In situations like these, typeof comparison is more reliable:
typeof x == 'undefined' // true
which will work properly in both cases: if variable has never been assigned a value, and if its value is actually undefined.
I guess both, depending on what you're testing? If it's a property, I'd always use x === undefined, since it's clearer (and it seems faster).
As others said, x === undefined won't work if x is not declared. Personally, I find that an even better reason to use it, since normally I shouldn't be checking if a variable is declared at all — it would usually be a sign of a coding mistake.
I've seen a lot of the other version for testing arguments — f = function(x) {if (typeof x == 'undefined') …} — if I'm code-reviewing code like this I'll tell them to change it. We know for a fact the variable is declared, and making an habit of writing it that way increases the chance you'll waste time chasing typo bugs.
The main exception is when you're trying to check if a component or library was loaded or initialized correctly. if (typeof jQuery == 'undefined') … makes sense. But in the medium term, all this should become modules anyway, in which case the typeof test should in my opinion be phased out as harmful.
(Also, personally, I prefer if (window.jQuery === undefined) for that case too. It's not portable for isomorphic code, though.)
x === undefined
does not work if variable is not declared. This returns true only if variable is declared but not defined.
Better to use
typeof x === 'undefined'
You could use any of them.
If you would like to check if a variable is undefined or null you could use:
x == null
This results in true if x is undefined or null.

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.

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

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.

What does the Javascript expression 'a = a || function() {...}' mean?

I'm not sure what this construct means but I've seen it a few times. The example below is from another Stack Overflow question. I'm not sure how to interpret the initial "or" construct itself:
Object.keys = Object.keys || (function () {
var hasOwnProperty = Object.prototype.hasOwnProperty,
hasDontEnumBug = !{toString:null}.propertyIsEnumerable("toString"),
DontEnums = [
'toString', 'toLocaleString', 'valueOf', 'hasOwnProperty',
'isPrototypeOf', 'propertyIsEnumerable', 'constructor'
],
DontEnumsLength = DontEnums.length;
//etc...
});
a = a || function(){...} is an idiom that is very common in Javascript. It relies on two concepts that, while not unique to Javascript, you might not yet be familiar with.
1. Operator short circuiting
Operator short circuiting[wikipedia] is a compiler optimization that was invented to prevent unnecessary evaluation.
To demonstrate this, let us suppose that we want to determine whether a person is a teenager: that is, whether a person has an age inclusively between 13 and 19 years.
var isTeenager = person.age >= 13 && person.age <= 19;
Now, let us suppose that the code executes and it turns out that the person is younger than 13. The first condition will be evaluated and will return false. Since the program now knows that the the left hand side of the && operator is false, and since && requires both sides to be true in order to evaluate to true, it knows that evaluating the right hand side is pointless.
In other words, the program, having seen that the person's age is not greater than 13, already knows that he is not a teenager and couldn't care less whether or not he is less than 19.
The same sort of principle applies to the || operator. Suppose we wanted to know if a person can ride the bus for free: that is, if the person is over 70 years old or is handicapped.
var canRideFree = person.age >= 70 || isHandicapped(person);
If the person is over 70, the program already knows that he can ride free. At this point, the program does not care if he is handicapped or not and thus does not evaluate the call to the isHandicapped function. If, on the other hand, the person was younger than 70, then canRideFree would be set to whatever isHandicapped returns.
2. Truthy and falsy values
Truthy and falsy values[some random person's blog] are the boolean evaluations of objects. In Javascript, every object will evaluate to either a "truthy" or a "falsy" value.
An expression is "falsy" if its value is any of these:
false, null, undefined, 0, "", NaN
Everything else is truthy.
People take advantage of the fact that a null or undefined variable evaluates to false. This means that you can check if a variable exists very easily:
if (a) { /* a exists and is not a falsy value */ }
Combining what we know
The || operator short circuits and returns the value of the last expression that it evaluates. This principle combines with truthiness in this single statement:
Object.keys = Object.keys || function() {...}
If Object.keys is truthy, it will be evaluated and assigned to itself. Otherwise, Object.keys will be assigned to the function. This is a very common idiom in Javascript for checking if a value already exists and assigning it to something else if it doesn't.
Some other languages, such as C#, that do not have truthiness, have a null-coalescing operator[MSDN] that has a similar purpose.
object Value = PossiblyNullValue ?? ValueIfNull;
In this code, Value will be assigned to PossiblyNullValue, unless it's null, in which case it will be assigned to ValueIfNull.
tl;dr [wikipedia]
If you didn't bother to read anything I said above, all you need to know is that a = a || function() {...} basically does what this code does:
if (exists(Object.keys)) {
Object.keys = Object.keys;
} else {
Object.keys = function() {...};
}
function exists(obj) {
return typeof obj !== "undefined" &&
obj !== null &&
obj !== false &&
obj !== 0 &&
obj !== "" &&
!isNaN(obj);
}
This looks incomplete to me, but it seems as if it is a shim for Object.keys. Basically, if the property doesn't exist (in non standards compliant browsers, for example), we implement it ourselves.
The or operator will evaluate the second operand only if the first one is falsy. As such
alert(false || "Hello, world");
Will alert "Hello, world". In this case, Object.keys would be undefined, which evaluates to false.
The || basically means: If Object.keys is not defined, define it using the expression behind the ||.
This behavior bases on the JavaScript feature that any variable that is undefined evaluates to false. If the variable is true, the second expression does not need to be evaluated, if it is false it does.
From what I can tell, that code attempts to define the function Object.keys if it isn't already defined (or if it's false). The function to the left of || will become the function Object.keys.
The reason I said "from what I can tell" is that you haven't posted the entire code snippet. Notice that the code after || reads (function(){ instead of just function(){. It's possible that the author has set up the function to be self invoking.
If, after the function definition, you see })(), then the return value of the function is stored in Object.keys. If not, then the function itself is stored there.

Categories

Resources