How to write an inline IF statement in JavaScript?

takeItEasy picture takeItEasy · Apr 22, 2012 · Viewed 555k times · Source

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

MattW picture MattW · Apr 22, 2012

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

var a = 2;
var b = 3;    
var c = ((a < b) ? 'minor' : 'major');

The c variable will be minor if the value is true, and major if the value is false.


This is known as a Conditional (ternary) Operator.

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