chackerian
chackerian

Reputation: 1401

Compare and assign numbers

This procedure has likely been covered on SO in some form but I do not know how to find it.

I would like to compare one value with two others and assign a variable ideally in the same step.

In my case, I have a user Id (A) and two sample user ids ( B and C )

Either B or C in this situation must be equal to A.

I want to check if A == B or A == C and then set a variable (other) to the B or C id that DOES NOT equal A.

I know I could do

 if (A == B) {
   var other = C;
   return other
 } 
 else {
   var other = B
   return other
 }

Simple enough but does anyone know of a more efficient way? Any JS libraries are allowed.

Upvotes: 3

Views: 134

Answers (2)

Rahul Tripathi
Rahul Tripathi

Reputation: 172568

Simple enough but does anyone know of a more efficient way?

You can use the if condition what you are using presently or you can use the ternary operator. Both are having the same performance. Its just the matter of readability to what you want to use. As far as performance is concerned both the ways are almost equally efficient.

Just saw this JSPerf test and found that if condition is faster than ternary condition.

Upvotes: 2

James Donnelly
James Donnelly

Reputation: 128786

You can do that with a ternary condition:

var other = A == B ? C : B;

In this case, if A and B are the same, other will be set to C, otherwise it'll be set to B.

Upvotes: 5

Related Questions