简体   繁体   中英

Javascript logical operators and results

I know that the result of logical operations in most of the languages is either true, false or 1,0. In Javascript I tried the following:

alert(6||5)  // => returns 6
alert(5||6)  // => returns 5
alert(0||5)  // => returns 5
alert(5||0)  // => returns 5
alert(5||1)  // => returns 5
alert(1||5)  // => returns 1
alert(5&&6)  // => returns 6
alert(6&&5)  // => returns 5
alert(0&&5)  // => returns 0
alert(5&&0)  // => returns 0
alert(-1&&5) // => returns 5
alert(5&&-1) // => returns -1  

So what is the result of logical operators? If one operand is 0 or 1 then it works as expected. If both are nonzero and other than 1 then

  1. In case of logical or , the first operand is returned
  2. In case of logical and , the second operand is returned

Is this the general rule?

Another thing I dont know is the operator | .

I have tried the operator | and gotten different results:

alert(5|8)  // => returns 13 
alert(8|5)  // => returns 13 
alert(-5|8) // => returs -5
alert(8|-5) // => returns -5
alert(0|1)  // => returns 1 
alert(1|0)  // => returns 1
alert(1|1)  // => returns 1

What does this operator actually do?

Since javascript is not a typed languaged any object can be used on logical operators, if this object is null, a false boolean, an empty string, a 0 or an undefined variable then it acts like a false if it's anything else then it is like a true

At the end of the logical operation the last checked value returns.

So

6||2

Check first value -> "6"
6 = true
Go to next value -> "2"
2 = true

End of operation, return last value. 2 which would work the same as true if passed to another logical operation.

Edit: that was a wrong statement. 6||2 returns 6 because 6 acting as true is enough to know the condition OR is true without the need to check the next value.

It is really the same way as in

true||true

Check first value -> "true"
Check next value -> "true"
return last value -> "true"

And for 6 && 0 && 2

First value 6 = true
Next value 0 = false

Stop operation here and returns the last checked value: 0.

The | operator is a whole different thing, it simply peforms a logical OR on the bits of the input values, as explaned on the other answer by akp.

Actually what you have derived are the pure digital results...like...

   3 in binary is 011......
   4 in binary is 100.....

   when u perform 3|4......

   it is equivalent to 011|100......i.e the OR operator which is the one of the bases of all logical operations

       011
       100

   will give 111 ie 7.............

   so u will get 3|4  as 7......

   hope u understand..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM