Semicolon
Semicolon

Reputation: 7413

Reference to Originating Conditional Value within a Javascript IF Statement

I often find that I write IF statements which immediately reference the value of the conditional statement. For example, let's say I need to check to see if a string matches a pattern:

if (mystring.match(/mypattern/) {
    var mymatch = mystring.match(/mypattern/)[1];
    ...
};

I suspect that what I'm looking for doesn't exist, but I've wondered whether you can reference the conditional statement's value within the if block, the way you can reference "arguments" within a function. In many cases, of course, I can rewrite it like this:

var mymatch = mystring.match(/mypattern/)[1];
if (mymatch) { ... };

But that's often not possible if there's a series of methods called. For example:

var mymatch = $('.myclass')[0].text().match(/mypattern/)[1];

... that would throw an exception if there were no item [0] on which to call .text(). Is there some convenient shorthand I'm missing out on? Or a better way to organize things? Just curious, really — I'll go on living if the answer is no.

Upvotes: 0

Views: 63

Answers (1)

Matt Whipple
Matt Whipple

Reputation: 7134

In cases where relevant you can use the fact that the assignment operator returns a value in JavaScript, so for instance you can write things like:

if (assignedTest = testedValue) {
   //value of assignedTest is now available 
   //and conditional will only be executed if true

This could be used if the RHS was compatible or properly set-up but it's also a huge readability concern since it's very easy to confuse the assignment = with comparison ==/===.

If you were particularly motivated to pursue this you could extract this type of functionality into a function that would behave in a reliable way: such as assigning the result of a closure to a named variable, and you could further tune the behavior to do other things (such as optionally evaluating to a different value within the test). Ultimately it would primarily be making a simple structure more complex though.

Upvotes: 1

Related Questions