Making shorthand from multiple IF / ELSE

I’m trying to make the following work in shorthand but I’m having some problems and I think it’s something to do with the way I’m clarifying the condition…


(class == \\'test1\\') ? file.href= dir+\\'test1.txt\\' : (class == \\'test2\\') ? test2.href= dir+\\'test2.txt\\' : file.href= dir+\\'test3.txt\\';

My attempt at shorthand:

class == (\\'test1\\') ? file.href= dir+\\'test1.txt\\' : (\\'test2\\') ? file.href= dir+\\'test2.txt\\' : file.href= dir+\\'test3.txt\\';

What am I doing wrong?

I see several inconsistancies between the “original” and “your attempt”.

Does the “original” work as it is?

Does (\‘string\’) return either boolean true or false?

Hi Mittineague, and yes, it does work with the original. When I look at the “attempt” I keep thinking to myself that I’m doing something wrong with the comparison as most IF shorthand statements that I’ve found on the internet seem to be assignment clauses. I know it shouldn’t matter, but I can’t help to think that.

If you try

var class = 'not_test_1';
var orig = (class == \\'test_1\\');
var attempt = class == (\\'test_1\\');

Do they both alert FALSE?

Note that class is a reserved word in ECMAScript and that it would be a really, really bad idea to use it as a variable name.

Thanks for the heads-up on that Tommy. I didn’t realize that. But yes, Mittineague, they both throw up “false” when the page loads.

Another area where there’s differences is

: (class == \\'test2\\') ? test2.href= dir+\\'test2.txt\\' :
: (\\'test2\\') ? file.href= dir+\\'test2.txt\\' :


var class = 'not_test2';
var orig = (class == \\'test2\\');
var attempt = (\\'test2\\');

Do both alerts still show boolean TRUE or FALSE ??

And is there a difference between using test2.href and file.href ??

Mittineague - First one shows “false” and the other shows “test2.” :slight_smile:

And for the difference, yes, there will be. In the example I provide, there isn’t, but in the actual website, the 2 different files each have their own different contents.

I’m guessing that the problem is the “test2”. AFAIK ternary conditionals need to return either boolean TRUE or FALSE, not a string. So if you change it to something like

: class == (\\'test2\\') ? file.href= dir+\\'test2.txt\\' :

that should fix things up, other than not using a reserved word for the variable name issue.

And I’m not sure that those escapes and parentheses are needed, but I guess that depends on what context you’re using this in.