Hi everone, I have this semplified code, I omiss the list of commands, ony the condition:
var IO1_0 = 1;
if (IO1_0 && 0) I have false, ok
if (IO1_0 && 1) I have true ok
if (IO1_0 && 2) I have true WHY?
if (IO1_0 == 2) I have false, ok
if (IO1_0 && 0x80) I have also true, WHY?
Thank you a lot, sincerely I don't know why they gave that meaning to it, I?ve lost almost an hour, I was thinking it was something else..
I solved in this way: if ((IO0_0 & 0x80)==0x80)
Please show a bit more sympathy for us refugees from C/C+/C#. Overloading of logical operators is standard in JavaScript but not automatic elsewhere. Correct me if I'm mistaken, but I believe that in most dialects of C, && can be overloaded by the user only if & is overloaded and at least some type checking is disabled -- not something that is done routinely.
Sorry mates, would better I argue more with the Javascript guide I read, they gave the same meaning I was addicted from C.. and I believed them.
There is any other symbol like && for C? ANd what about ||? I saw it was used to inizialize a variable if it is the first time declared propbably if it property is "udefined"?
Thank you
Actually, I take it back, && isn't the same as C at all as it returns one of the original values rather than true or false.
However, going back to your original question, the expressions you were not happy with were 1 && 2 which tests true and 1 && 0x80 which also tests true.
I believe I am right in saying that in C both of those would also return true. It is a long time since I used C however, so I may be wrong here too. I have just looked in my well thumbed 1978 version of Kernighan and Ritchie and I think that is right.
||, logical OR is also very similar to that in C. If either of the values can be considered truethy then the result will also be truethy. It can be used in initialising because undefined is falsey so, for example, someValue || 0 will give 0 if someValue is undefined, as undefined is considered falsey.
I have just run some tests to check what happens with C to compare with Javascript. The conclusion is that the if statements
if (a && b)
if (a || b)
give the same results in js and C.
The difference arises with
int i = a && b;
int j = a || b;
and
var i = a && b;
var j = a || b;
where C always returns 1 or 0 whereas js returns either a or b (but both will be interpreted the same when used in an if statement.
So for the examples @GiovanniG gave at the start, the results are the same in C or js.
Nice work, @Colin. Old-fashioned C (before C99) secretly wanted the arguments and result of && to be boolean, but did not have a boolean data type. It used (integer) 0 for false and anything non-zero interpreted as true. Later versions and dialects have boolean data types but maintain backward compatibility. @GiovanniG missed the point that 2 and 0x80 are true in this context.