can I use `else if` with a ternary operator? - javascript

Can I only use if and else in a statement in ternary operator syntax or can I also somehow include an else if?
example:
if(a) {
x
}
else if(y) {
c
}
else {
b
}

Unlike an if with optional else or optional else if branches, a ternary operator has two and only two branches.
It's actually a part of the name. Where + in a + b is a binary operator, that is it has two operands, ? has three, as in a ? b : c, and is termed ternary because of that. Technically there could be other ternary operators beyond ? but in most languages they don't exist, so it is generally understood that the name "ternary" means the ? operator.
You can have else if like functionality if you sub-branch the second clause:
a ? b : (c ? d : e)
This is usually a bad idea as ternary operations can be messy to start with and layering like this is usually an express train to unmaintainable code.
It is much better to write:
if (a) {
b
}
else if (c) {
{
d
}
else {
e
}
This is more verbose, but abundantly clear.
If you use ternaries too agressively you'll end up with code like:
a()?c?d?e:f:g:h?i(j?k:l?m:n):o
Where it's anyone's guess what's going on in there.

It's very much possible!
You could use this:
a ? b : b ? c : d

You could stack multiple ternaries:
var x = (y) ? 1 : ( (z) ? 2 : 0 );

Related

What is this called, and how would I use it for a lockdown command [duplicate]

This question already has answers here:
What is the Java ?: operator called and what does it do?
(17 answers)
Closed 7 years ago.
Two questions about using a question mark "?" and colon ":" operator within the parentheses of a print function: What do they do? Also, does anyone know the standard term for them or where I can find more information on their use? I've read that they are similar to an 'if' 'else' statement.
int row = 10;
int column;
while (row >= 1)
{
column = 1;
while(column <= 10)
{
System.out.print(row % 2 == 1 ? "<" : "\r>");
++column;
}
--row;
System.out.println();
}
This is the ternary conditional operator, which can be used anywhere, not just the print statement. It's sometimes just called "the ternary operator", but it's not the only ternary operator, just the most common one.
Here's a good example from Wikipedia demonstrating how it works:
A traditional if-else construct in C, Java and JavaScript is written:
if (a > b) {
result = x;
} else {
result = y;
}
This can be rewritten as the following statement:
result = a > b ? x : y;
Basically it takes the form:
boolean statement ? true result : false result;
So if the boolean statement is true, you get the first part, and if it's false you get the second one.
Try these if that still doesn't make sense:
System.out.println(true ? "true!" : "false.");
System.out.println(false ? "true!" : "false.");
Thats an if/else statement equilavent to
if(row % 2 == 1){
System.out.print("<");
}else{
System.out.print("\r>");
}
a=1;
b=2;
x=3;
y=4;
answer = a > b ? x : y;
answer=4 since the condition is false it takes y value.
A question mark (?)
. The value to use if the condition is true
A colon (:)
. The value to use if the condition is false
Also just though I'd post the answer to another related question I had,
a = x ? : y;
Is equivalent to:
a = x ? x : y;
If x is false or null then the value of y is taken.
Maybe It can be perfect example for Android,
For example:
void setWaitScreen(boolean set) {
findViewById(R.id.screen_main).setVisibility(
set ? View.GONE : View.VISIBLE);
findViewById(R.id.screen_wait).setVisibility(
set ? View.VISIBLE : View.GONE);
}
They are called the ternary operator since they are the only one in Java.
The difference to the if...else construct is, that they return something, and this something can be anything:
int k = a > b ? 7 : 8;
String s = (foobar.isEmpty ()) ? "empty" : foobar.toString ();
it is a ternary operator and in simple english it states "if row%2 is equal to 1 then return < else return /r"

What is the use of "?" in jquery

What is the use of "?" mark ?
can anyone explain what question mark is doing here.
0 ? 1 : 1+w
and also ":" symbol .
How to use "?" while writing the codes..
I have seen so many codes where people will use "?" like example above.
can anyone explain what question mark is doing.
This is nothing to do with jquery, this is standard javascript. It's known as a ternary operator. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator
This:
x = a ? b : c
is the equivalent of writing:
if (a) {
x = b
} else {
x = c
}
It has nothing to do with jquery. it is javascript if else shorthand method
Check below example
var big;
if (x > 10) {
big = true;
}
else {
big = false;
}
shorthand
var big = (x > 10) ? true : false;
That's called ternary operator, a kind of conditional operator
var fooNotNull = (foo !== null) ? true : false;
if the first condition is 'true', it is saved in the variable 'fooNotNull', else the second value 'false' is stored in 'footNotNull'
The expression is a tenerary operator. It works like an 'if' and 'else'.
Whatever is before the '?' is evaluated, returning what is after the '?' when the condition is true, and whatever is after the ':' if it is false.
These expressions give the same results:
a = 0 ? 1 : 1+w
if(0){
a = 1;
}else{
a = 1 + w;
}

javascript two "?" operators one by one

Help me please understand how this piece of code are working.
function getOpacity( elem ) {
var filter = elem.style.filter;
return filter ?
filter.indexOf("opacity=") >= 0 ?
(parseFloat(filter.match(/opacity=([^)]+)/)[1]) / 100) + "" :
"" :
elem.style.opacity;
}
I was try console.log(filter) and received empty string. I thing something interesting going on with two "?" operators. I know for what there is one "?". But i need help with two such operators.
It's just nested conditional (i.e. ?:) operators. This code is equivalent to:
if (filter) {
if (filter.indexOf("opacity=") >= 0) {
return (parseFloat(filter.match(/opacity=([^)]+)/)[1]) / 100) + "";
} else {
return "";
}
} else {
return elem.style.opacity;
}
The default precedence for
a ? b : c ? d : e
is
a ? b : (c ? d : e)
and not, for example
(a ? b : c) ? d : e
This makes it easy to use the ? ternary operator much like a series of if/then/else statements without superfluous parentheses, although you're welcome to add them if you think they improve readability.

What a strange syntax?

I've found unknown for me code construction on JQuery site. After some formatting it looks like:
function (a,c) {
c==null && (c=a,a=null);
return arguments.length>0
? this.bind(b,a,c)
: this.trigger(b)
}
What does the first line of the function mean? Is it any trick or standard JS code construction?
It's a trick that uses boolean short-circuit evaluation to only do the second half if the first evaluates to true. Perl has this commonly:
<something> or die
where if the first statement failed, the program ends.
Read it as
if (c == null) { c = a; a = null; }
That's an ugly way to write
if(c==null) {
c = a;
a = null;
}
This utilizes the fact, that the second part of boolean && will be executed if, and only if the first part evaluates to true.
The expression uses two JavaScript features :
short circuit evaluation of boolean operators: in statement context, a && (b); is equivalent to if (a) (b);
the comma operator to group assignment expressions: in statement context, a=b,b=c; is equivalent to { a=b; b=c }
As a result the expression is equivalent to:
if (c == null) {
c = a
a = null
}

Is there anyway to implement XOR in javascript

I'm trying to implement XOR in javascript in the following way:
// XOR validation
if ((isEmptyString(firstStr) && !isEmptyString(secondStr)) ||
(!isEmptyString(firstStr) && isEmptyString(secondStr))
{
alert(SOME_VALIDATION_MSG);
return;
}
Is there a better way to do this in javascript?
Thanks.
As others have pointed out, logical XOR is the same as not-equal for booleans, so you can do this:
// XOR validation
if( isEmptyString(firstStr) != isEmptyString(secondStr) )
{
alert(SOME_VALIDATION_MSG);
return;
}
I pretend that you are looking for a logical XOR, as javascript already has a bitwise one (^) :)
I usually use a simple ternary operator (one of the rare times I use one):
if ((isEmptyString(firstStr) ? !isEmptyString(secondStr)
: isEmptyString(secondStr))) {
alert(SOME_VALIDATION_MSG);
return;
}
Edit:
working on the #Jeff Meatball Yang solution
if ((!isEmptyString(firstStr) ^ !isEmptyString(secondStr))) {
alert(SOME_VALIDATION_MSG);
return;
}
you negate the values in order to transform them in booleans and then apply the bitwise xor operator. Maybe it is not so maintainable as the first solution (or maybe I'm too accustomed to the first one)
You are doing an XOR of boolean values which is easy to model into a bitwise XOR (which Javascript has):
var a = isEmptyString(firstStr) ? 1 : 0;
var b = isEmptyString(secondStr) ? 1 : 0;
if(a ^ b) { ... }
http://www.howtocreate.co.uk/xor.html
You could use the bitwise XOR operator (^) directly:
if (isEmptyString(firstStr) ^ isEmptyString(secondStr)) {
// ...
}
It will work for your example since the boolean true and false values are converted into 1 and 0 because the bitwise operators work with 32-bit integers.
That expression will return also either 0 or 1, and that value will be coerced back to Boolean by the if statement.
You should be aware of the type coercion that occurs with the above approach, if you are looking for good performance, I wouldn't recommend you to work with the bitwise operators, you could also make a simple function to do it using only Boolean logical operators:
function xor(x, y) {
return (x || y) && !(x && y);
}
if (xor(isEmptyString(firstStr), isEmptyString(secondStr))) {
// ...
}
Easier one method:
if ((x+y) % 2) {
//statement
}
assuming of course that both variables are true booleans, that is, 1 or 0.
If x === y you'll get an even number, so XOR will be 0.
And if x !== y then you'll get an odd number, so XOR will be 1 :)
A second option, if you notice that x != y evaluates as a XOR, then all you must do is
if (x != y) {
//statement
}
Which will just evaluate, again, as a XOR. (I like this much better)
Of course, a nice idea would be to implement this into a function, but it's your choice only.
Hope any of the two methods help someone! I mark this answer as community wiki, so it can be improved.
Checkout this explanation of different implementations of XOR in javascript.
Just to summarize a few of them right here:
if( ( isEmptyString(firstStr) || isEmptyString(secondStr)) && !( isEmptyString(firstStr) && isEmptyString(secondStr)) ) {
alert(SOME_VALIDATION_MSG);
return;
}
OR
if( isEmptyString(firstStr)? !isEmptyString(secondStr): isEmptyString(secondStr)) {
alert(SOME_VALIDATION_MSG);
return;
}
OR
if( (isEmptyString(firstStr) ? 1 : 0 ) ^ (isEmptyString(secondStr) ? 1 : 0 ) ) {
alert(SOME_VALIDATION_MSG);
return;
}
OR
if( !isEmptyString(firstStr)!= !isEmptyString(secondStr)) {
alert(SOME_VALIDATION_MSG);
return;
}
Quoting from this article:
Unfortunately, JavaScript does not have a logical XOR operator.
You can "emulate" the behaviour of the XOR operator with something like:
if( !foo != !bar ) {
...
}
The linked article discusses a couple of alternative approaches.
XOR just means "are these two boolean values different?". Therefore:
if (!!isEmptyString(firstStr) != !!isEmptyString(secondStr)) {
// ...
}
The !!s are just to guarantee that the != operator compares two genuine boolean values, since conceivably isEmptyString() returns something else (like null for false, or the string itself for true).
Assuming you are looking for the BOOLEAN XOR, here is a simple implementation.
function xor(expr1, expr2){
return ((expr1 || expr2) && !(expr1 && expr2));
}
The above derives from the definition of an "exclusive disjunction" {either one, but not both}.
Since the boolean values true and false are converted to 1 and 0 respectively when using bitwise operators on them, the bitwise-XOR ^ can do double-duty as a logical XOR as well as a bitwiseone, so long as your values are boolean values (Javascript's "truthy" values wont work). This is easy to acheive with the negation ! operator.
a XOR b is logially equivalent to the following (short) list of expressions:
!a ^ !b;
!a != !b;
There are plenty of other forms possible - such as !a ? !!b : !b - but these two patterns have the advantage of only evaluating a and b once each (and will not "short-circuit" too if a is false and thus not evaluate b), while forms using ternary ?:, OR ||, or AND && operators will either double-evaluate or short-circuit.
The negation ! operators in both statements is important to include for a couple reasons: it converts all "truthy" values into boolean values ( "" -> false, 12 -> true, etc.) so that the bitwise operator has values it can work with, so the inequality != operator only compares each expression's truth value (a != b would not work properly if a or b were non-equal, non-empty strings, etc.), and so that each evaluation returns a boolean value result instead of the first "truthy" value.
You can keep expanding on these forms by adding double negations (or the exception, !!a ^ !!b, which is still equivalent to XOR), but be careful when negating just part of the expression. These forms may seem at first glance to "work" if you're thinking in terms of distribution in arithmatic (where 2(a + b) == 2a + 2b, etc.), but in fact produce different truth tables from XOR (these produce similar results to logical NXOR):
!( a ^ b )
!( !!a ^ !!b )
!!a == !!b
The general form for XOR, then, could be the function (truth table fiddle):
function xor( a, b ) { return !a ^ !b; }
And your specific example would then be:
if ( xor( isEmptyString( firstStr ), isEmptyString( secondStr ) ) ) { ... }
Or if isEmptyString returns only boolean values and you don't want a general xor function, simply:
if ( isEmptyString( firstStr ) ^ isEmptyString( secondStr ) ) { ... }
Javascript does not have a logical XOR operator, so your construct seems plausible. Had it been numbers then you could have used ^ i.e. bitwise XOR operator.
cheers
here's an XOR that can accommodate from two to many arguments
function XOR() {
for (var i = 1; i < arguments.length; i++)
if ( arguments[0] != arguments[i] )
return false;
return true;
}
Example of use:
if ( XOR( isEmptyString(firstStr), isEmptyString(secondStr) ) ) {
alert(SOME_VALIDATION_MSG);
return;
}
I hope this will be the shortest and cleanest one
function xor(x,y){return true==(x!==y);}
This will work for any type
Here is an XOR function that takes a variable number of arguments (including two). The arguments only need to be truthy or falsy, not true or false.
function xor() {
for (var i=arguments.length-1, trueCount=0; i>=0; --i)
if (arguments[i])
++trueCount;
return trueCount & 1;
}
On Chrome on my 2007 MacBook, it runs in 14 ns for three arguments. Oddly, this slightly different version takes 2935 ns for three arguments:
function xorSlow() {
for (var i=arguments.length-1, result=false; i>=0; --i)
if (arguments[i])
result ^= true;
return result;
}
Try this:
function xor(x,y)
var result = x || y
if (x === y) {
result = false
}
return result
}
There's a few methods, but the ternary method (a ? !b : b) appears to perform best. Also, setting Boolean.prototype.xor appears to be an option if you need to xor things often.
http://jsperf.com/xor-implementations
You could do this:
Math.abs( isEmptyString(firstStr) - isEmptyString(secondStr) )
The result of that is the result of a XOR operation.
#george, I like your function for its capability to take in more than 2 operands. I have a slight improvement to make it return faster:
function xor() {
for (var i=arguments.length-1, trueCount=0; i>=0; --i)
if (arguments[i]) {
if (trueCount)
return false
++trueCount;
}
return trueCount & 1;
}

Categories

Resources