takeItEasy takeItEasy - 4 months ago 18
Javascript Question

How to write an inline IF statement in JavaScript?

How can I use an inline

if
statement in JavaScript? Is there an inline
else
statement too?

Something like this:

var a = 2;
var b = 3;

if(a < b) {
// do something
}

Answer

You don't necessarily need jQuery. JavaScript alone will do this.

var a = 30;
var b = 40;    
var c = ((a < b) ? 2 : 3);

There 2 is the value when true, 3 is the value when false.


This is known as a Conditional (ternary) Operator.

https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/Conditional_Operator

Comments