# What does this construct do {flag = flag | a;}?

I’m trying to reuse some old code I wrote and forget where I found the syntax(I’m no expert - probably fit better in the ‘dabbler’ category).

``````if(pmIn != ""){flag = flag | a;}
``````

Is this a short cut for the ternary operator? As in

``````flag = (pmIn != "") ? flag : a
``````

or

``````if(pmIn != ""){flag = flag;} else {flag = a;}
``````

Thanks

No. It would be if it had || between the two values though instead of the single |.

One | by itself is a bitwqise or operator and so the value returned from flag | a will be a value with bits set on where ever either of those two values had the bit set on.

Thanks, now I remember what I was doing. Here’s the whole snippet

``````//get combinations of times
//
var flag = 0;
var a = 1;
var b = 2;
var c = 4;
var d = 8;

if(amIn != ""){flag = flag | a;}
if(amOut != ""){flag = flag | b;}
if(pmIn != ""){flag = flag | c;}
if(pmOut != ""){flag = flag | d;}

switch(flag)
{
case 3:
bb = cTFD_03(amIn, amOut);	//, hrs);
break;
case 9:
cTFD_09(amIn, pmOut);	//, hrs);
break;
case 12:
cTFD_12(pmIn, pmOut);	//, hrs);
break;
case 15:
cTFD_15(amIn, amOut, pmIn, pmOut);	//, hrs);
break;
default:
break;
}
``````

So when different combinations of the if’s are true it produces different values for flag, then I use that value in the switch statement.
Just proves what a waste of time comments are.

The added complexity doesn’t provide much of any benefit either.
Have a look at the following, which performs the same job in an easier to understand manner:

``````
if (amIn && amOut && pmIn && pmOut) {
cTFD_15(amIn, amOut, pmIn, pmOut);
} else if (amIn && amOut) {
cTFD_03(amIn, amOut);
} else if (amIn && pmOut) {
cTFD_09(amIn, pmOut);
} else if (pmIn && pmOut) {
cTFD_12(pmIn, pmOut);
}

``````

Then it’s just a matter of giving the functions suitably descriptive names.

Also bitwise operators in JavaScript are extremely inefficient - unlike most other languages where they are amongst the fastest operations, in JavaScript they are the slowest by a long way.

Thanks for the speedy help and tips everyone. I’ll be sure to try here again next time I forget what I’ve done (or need help doing something I’ve never done.)