Ternary Operator | SoloLearn: Learn to code for FREE!


Ternary Operator

I'm yet to understand this code: var age = 42; var isAdult = (age < 18) ? "Too young": "Old enough"; document.write(isAdult); < means less than > means greater than if it is true, why is the statement below correct? This is because age(45) is greater than 18. Why will the result be Old enough and not Too young?

6/30/2018 9:11:48 PM


6 Answers

New Answer


See the ternary operator like this. is age (42) < (less than) 18? YES DO THIS PART : NO DO THIS PART



Thanks man.


The ternary operator evaluates an expression like the if-else statement. if(exp){ //code to run } else{ //code to run } Just in the same vein the ternary operator performs the same operation on a line: exp? TRUE : FALSE.


I'll give you a nice example: int max4(int a,int b,int c,int d) { int t1=(a>b)?a:b; int t2=(c>d)?c:d; return (t1>t2)?t1:t2; }


Basically, it is like a simple if-else situation, abbreviated. String x; if(2>1) x = "two"; else x = "one"; This translates to: String x; x = 2>1? "Two": "one";