Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript coding technique or bad code?

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?

like image 422
Silkster Avatar asked Nov 03 '10 20:11

Silkster


2 Answers

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');
like image 182
Harmen Avatar answered Sep 30 '22 17:09

Harmen


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:

  1. Make sure the identifier exist, and
  2. Make sure it is callable

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.

like image 34
Christian C. Salvadó Avatar answered Sep 30 '22 16:09

Christian C. Salvadó