I keep seeing this syntax, but I don't know what's it's called or what it does:
can someone please explain this?Code:thing == 0 ? "a" : "b" + thing
thanks
Printable View
I keep seeing this syntax, but I don't know what's it's called or what it does:
can someone please explain this?Code:thing == 0 ? "a" : "b" + thing
thanks
That is considered a conditional operator in javascript. Essentially you have 3 parts
thing == 0 ? "a" : "b" + thing
The first part is a condition or comparison. If this condition is true then the second part is the value that is returned. If that condition is false then the third and final part is returned instead. So if 'thing' is equal to 0 then that statement would return "a", otherwise it will return "b" + thing.
thanks :)
thing == 0 ? "a" : "b" + thing
is shorthand for
if (thing == 0) {
return "a";
} else {
return "b" + thing;
}
^ Except you don't return from a function when using ?: . A better example might be
a = b ? c : d;
which would be shorthand for
if (b) {
a = c;
} else {
a = d;
}