Ternary not Explanatory
Helpful inline variable assignment
November 03, 2018Question: What the heck is a Ternary Operator?
Answer 1: "An inline variable assignment."
Answer 2 below:
var x = (b) ? a : c;
Answer 3:
ne day I found myself in a JavaScript class - a real live class at a college with wooden desks and a "professor". He wrote this:
var x = (b) ? a : c;
on the chalk board (ok maybe a white board with markers) and a few other lines of code before and after it. I raised my hand and asked what the heck that line meant. Weird, because I had been coding for a long time (note: not much in C) and I hadn't seen that used before.
He said, "What do you mean?" I asked again. He said rolling his eyes, "It's a Ternary Operator."
"Oh", said I. "So you don't know either."
He took 10 minutes of mumbling, stumbling and eventually giving up to write the other 40 lines of code that he didn't really understand onto the board -which I ended up explaining to the class. At the end, a friend explained the Terderary thing to me. Sometimes, I'm glad I didn't waste 6 figures on schooling.
Anyways, it's a lot easier than it looks and it comes in handy quite a bit. Unfortunately, it can read very confusing and mess up some otherwise, elegant coding.
Here's the super short and sweet simple version:
A Ternary Operator is: an if-then-else value assignment.
Code please :
var a = 'a';
var b;
var c = 'c';
var x = (b) ? a : c;
alert(x);
You probably get it by now, but in English, it's simply variable x
= if my statement in the parentheses is true, then use the value after the question mark, else use the value after the colon.
Got it? I figured. Here's a cool line of code I just used it in to get the opposite angle of a direction heading:
var angleY = (Number(angle) > 179) ? Number(angle) - 180 : Number(angle) + 180;
Handy Yeah?
BTWs, (By The Way or Bestest Thou Watchest) most other languages have some sort of version of this and most of them use the ? and :. However, watch out for the Python implementation. I really don't even think it's a good idea to use it there and it's pretty backwards anyways. I often will not sacrifice elegance for convenience.