2

The following syntax works perfectly fine in PHP:

if($data = check_database($conds)) var_dump($data);
else echo "Not found";

However, in Javascript, I can't find an equivalent shorthand:

/*THIS CREATES A GLOBAL VARIABLE:*/
if(data = check_database(conds)) console.log(data);
else console.log("Not found.");


/*THIS RESULTS IN A SYNTAX ERROR (unexpected token var):*/
if(var data = check_database(conds)) console.log(data);
else console.log("Not found.");

Is there a way for me to declare a locally-scoped var in Javascript within the if (and other) statement(s). NOTE: This is not a problem for the for statement which expects complete statements as arguments.

Ultimately, I want to avoid the following verbose syntax:

/*THIS HAS THE DESIRED EFFECT, BUT UNDESIRED (VERBOSE) SYNTAX*/
var data;
if(data = check_database(conds)) console.log(data);
else console.log("Not found.");
Femi
  • 1,332
  • 9
  • 20
  • 1
    Ultimately, running an assignment in an if statement is a maintenance hazard. Get used to doing things this way and consequently suffer a bunch of bugs because you now fail to know when you're assigning and when you're comparing. I mean then look somewhat similar, don't they? Do one thing on one line. Verbosity is good. Brevity at the expense of clarity... really? – spender Sep 07 '14 at 19:59

2 Answers2

5

The answer here is that you shouldn't be trying to write code like that in the first place.

You may have confidence in your clever, minimalist code, but someone reading it is going to have to expend time and energy figuring out whether you really meant to use a single =, or made a typo trying to type ==.

Just write code that's clear in its intent and leaves minimal room for bugs to creep in. A few extra lines are not going to hurt you:

var data = check_database(conds);
if (data) {
    console.log(data);
} else {
    console.log("Not found.");
}


Addendum: If you truly find it distasteful to have to use the data variable three times instead of twice, then an alternative is to write a helper function:
function handleData(data, success, failure) {
    if (data) {
        success(data);
        return data;
    }

    failure();
    return null;
}

And then you can use it like this:

handleData(check_database(conds), function (data) {
    console.log(data);
}, function () {
    console.log("Not found.");
});

This uses one line less than my original example, but introduces a lot of unneeded overhead and headaches making sure all the braces and parentheses match up. Plus it's less clear because people reading it need to figure out/remember what the helper function does.

JLRishe
  • 99,490
  • 19
  • 131
  • 169
  • I understand (+1). This is not the proper way to write maintainable code. But this does not deter my interest in finding a solution. There are times when it may be useful - especially in a data-based application where this same type of operation occurs dozens of times, it's clear that my intention is to attempt data retrieval then work with it, but on failure provide an error or execute some alternative code. I would still like a correct answer. – Femi Sep 07 '14 at 20:05
  • 1
    I'm not sure I see your point. How is it any different if you have to do this dozens of times? That just means that you'd potentially have dozens of instances of hard-to-maintain code. What's so bad about having one line for the data retrieval, and one line for the `if`? Can you provide an example of a case where my example is not a workable alternative to what you have above? – JLRishe Sep 07 '14 at 20:15
  • 1
    I'd love to challenge this notion that declaring a variable inside an if condition is somehow less maintainable. Seems subjective to me. I've seen this many times in highly maintained code. Granted that's just an anecdote, but that's all that's been provided here to the contrary. – Tony Topper Nov 21 '14 at 17:54
  • @AnthonyTopper "Maintainable" and "highly maintained" are two separate things. I have no doubt that there is a lot of professional-grade software that uses assignments inside `if` conditions. I'm sure there's a lot of it, but that doesn't mean it's a good idea. There are even some coding standards (such as MISRA 2004, see rule 13.1) that prohibit using assignments in boolean control expressions. – JLRishe Dec 18 '14 at 17:05
  • @JLRishe If you want to get pedantic the only discernible way to judge something without a mathematically discrete definition, aka "maintainable" is to see if it actually is "maintained". Granted even that is really subjective, but it's probably the best gauge to authentic maintainability. Thanks for the reference to a coding standard. – Tony Topper Dec 19 '14 at 20:39
0

This specific example it looks like you can re-write as

console.log( check_database(conds) || "Not found." );

But usually, you'd be left doing:

if ( check_database(conds) ){
    console.log( data );
}
else {
    console.log( "Not found." );
}

or

var data = check_database(conds);
// maybe some other stuff
console.log( data || "Not found." );

or even

var data = check_database(conds);
if ( data ){
    // some if true stuff
    console.log( data );
}
else {
    // some if false stuff
    console.log( "Not found." );
}
iabw
  • 1,108
  • 1
  • 9
  • 24
  • I know - it's a contrived example :). The actual code in the TRUE branch can be much more complex and does not yield itself to this shorthand. – Femi Sep 07 '14 at 19:55