1

Suppose I have a code like this:

i=1;
if(i===1)
{
    i++;
}

This code does have a if block but no else block. So,my question is , how to accomplish the same thing with the ternary operator. I had tried something like this:

i=1;
i===1? i++

But got an error :

SyntaxError: Unexpected end of input.

UPDATE:

So,now I change my question and ask do ternary operators need an else block in all cases?

6
  • Why do you want to make something hard to read? Commented May 4, 2013 at 2:41
  • This a sample code.I just wanted some knowledge on if ternary operators need an else block in all cases. Commented May 4, 2013 at 2:43
  • Do you just need a ; at the end of your statement? Commented May 4, 2013 at 2:48
  • Added a semi-colon here,final code: i=1; i===1? i++; but new error says "SyntaxError: Unexpected token ;" Commented May 4, 2013 at 2:51
  • 1
    In javascript and PHP, it's neccessary. Commented May 4, 2013 at 3:12

2 Answers 2

3
i = i===1 ? i+1 : i;

or

i += i===1 ? 1 : 0;

But you probably want to use if for this. The ternary is less clear.

And yes this means that ternary always needs an else. The definition of ternary is "composed of 3 parts" if that helps clarify.

Sign up to request clarification or add additional context in comments.

3 Comments

So,does it mean that ternary operators need an else code in all cases?
If you want to test truthyness or falsyness you can just use short-circuit operators: i=1; i==1 && i++;
@GaurangTandon Yes, its syntactically required. Of course, depending on how you use it or what you do with it, you can always execute a function that does nothing, return a default value, or use void(0)
2

Actually, you CAN do a sort of ternary without the else.

It's not technically a ternary, but serves the same purpose, and has a similarly spiffy simplified format.

It's a trick called Short Circuiting.

    i===1 && i++;

See, that code is treated as a pair of "if" tests connected by AND. When you do a series of AND conditional tests, the moment any of them fail (parsing left to right) the rest are ignored.

So you can put any assignment or operation after a test, and it will only happen if the test succeeds.

    refrigerator && beer();

...will only run beer if there is refrigerator.

    refrigerator && beer() && drunk = "Woah Nelly";

...will only run beer if refrigerator is truthy, and only if beer returns truthy will drunk be set to "Woah Nelly".

If it gets complicated, you can format it like this:

    refrigerator 
        && beer() 
        && drunk == "Woah Nelly"
        && toilet = barf();

In your case, only if i is equal to a strictly typed 1 is it incremented by the ++;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.