While debugging javascript written by someone else, I came across some code that I've not seen before. Here's a sample:
function doSomething() {
//doing something here...
}
function doItNow() {
//other logic...
doSomething && doSomething(); // <=== What's this?
}
Is the purpose of the 2nd line in function doItNow() to check if doSomething exists and then call it? Like so:
function doItNow() {
//other logic...
if (doSomething) {
doSomething();
}
}
JSLint does not like it and I'd rather not have bad code in my app. Any insights?
It's a 'shorthand' indeed. The right side is only executed when the left side passes as if()
statement.
Google Closure Compiler and other minifiers take advantage of this; if your input is if(a) a()
, it will result in a&&a()
You could do the same with ||
, for example:
if( !a ){
alert('Not a');
}
can be written as
a || alert('Not a');
Yes, your two examples are "equivalent", the &&
operator performs short-circuit evaluation.
If the first operand expression yields a falsey value (such as null
, undefined
, 0
, NaN
, an empty string, and of course false
), the second operand expression will not be evaluated, and if the value is truthy, the function call will be made.
But if doSomething
hasn't been declared, your both examples will fail.
If an identifier that's not declared, is referenced on code, you will get a ReferenceError
exception, e.g.:
function foo() {
undeclared && undeclared();
}
try {
foo();
} catch (e) {
alert(e); // ReferenceError!
}
If you want to:
You can:
if (typeof doSomething == 'function') {
doSomething();
}
The typeof
operator can be safely used on identifiers that don't exist, additionally, by checking that doSomething
is a function, you make sure that you will be able to invoke it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With