1

I tried if else in javascript using ? : Ex : (i > 0 ? 'test': 'test1')

But i need if() { } esle if() { } else if() { } else (){ } using ? : operators Reason am using operators is am appending the table in Jquery so i need to write the logic in between append statements

can any one help me in this

1
  • 2
    Why not use switch? It's easier to read and change/add code when needed. Commented Aug 5, 2015 at 6:23

4 Answers 4

5
var value = Cond1 ? True1 : (Cond2 ? True2 : (Cond3 ? True3 : Other));

The () notations make the expression above clear, but not a must do.

Demo:

var a;
for (var i = 0; i < 5; ++i) {
  a = (i === 0 ? 'Zero' : (i === 1) ? 'one' : (i === 2) ? 'two' : 'Other');
  console.log(a);
}

However, I'd suggest use

var str;
if () {
  str = ...
} else if() {
  str = ...
}
// Or .append/.html  ...etc.
$TBL.text('....' + str + '.....');

For readability.

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

Comments

1

With switch your code will be easier to read and it's also easy to add or change a case.

var i = 0;
switch(i) {
    case 0:
        //i is 0
        break;
    case 1:
        //i is 1
        break;
    case 2:
        //i is 2
        break;
    case 3:
        //i is 3
        break;
    case 'foobar':
        //this is not an integer
        break;
    default:
        //i is not one of the above
}

1 Comment

of course ternary operator is good when You've simple form: (condition)? iftrue : iffalse . but everybody must agree that when we have complex conditions it's better to use switch..case
0

You can use iternary operator in the following way to get the result:

Check_1 ? true_1 : (Check_2 ? true_2 : (Cond_3 ? true_3 : ....));

Comments

0

you can use ElseIf condition in javascript like this

var time = new Date().getHours();
    if (time < 10) {
        greeting = "Good morning";
    } else if (time < 20) {
        greeting = "Good day";
    } else {
        greeting = "Good evening";
    }

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.