0

I am checking for the values of AND operator in javascript, the below code for some reason returning 0. Can someone explain actual behavior of AND operator here?

var result = 88 && 6 && 0 && null && 9;
alert(result);
Qantas 94 Heavy
  • 15,750
  • 31
  • 68
  • 83
karthik_spain
  • 331
  • 1
  • 2
  • 8
  • 1
    See here http://en.wikipedia.org/wiki/Short-circuit_evaluation – elclanrs Jul 16 '14 at 10:51
  • Returns the thing on the left if it is falsy, the thing on the right otherwise. So in a chain it returns the first falsy thing, or the last thing in the chain if they are all truthy. So `0`. – Niet the Dark Absol Jul 16 '14 at 10:52
  • 1
    @elclanrs: short circuit evaluation doesn't enter into it... there are no `||` operators here, just two falsy operands (`0` and `null`). The only thing to note is that `null` and `9` will not be evaluated, because the `&& 0` part ensures that the expression will be false – Elias Van Ootegem Jul 16 '14 at 10:56
  • What do you expect to happen? You know that && is the AND operator already. – Qantas 94 Heavy Jul 16 '14 at 11:24

1 Answers1

5

&& evaluates as the left hand side if the left hand side is false, otherwise it evaluates as the right hand side.

(88) && (6 && 0 && null && 9)

88 is true, so the right hand side is evaluated.

(6) && (0 && null && 9)

6 is true, so the right hand side is evaluated.

(0) && (null && 9)

0 is false, so it is the result.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335