Skip to content Skip to sidebar Skip to footer

What's The Difference Between These Two Uses Of The && Logical Operator?

What is the difference between these various uses of the '&&' logical operator? From Oliver Steele's Functional.js library. Line 4, 'args.length && arg': 0 Function

Solution 1:

Well, it's the same operator everywhere, but being used for different purposes by the programmer.

The first code example is not doing args.length && arg at all, but is rather doing the equivalent of (i < args.length) && (arg < arguments.length) because && has lower precedence than <. It means, "loop until either i is at or surpasses the argument count or arg is at or surpasses the argument count". You can see that + is therefore not equivalent in this context.

The other code examples are all exploiting the fact that the logical-and operator (&&) "short-circuits" when its left-hand operand is false, i.e. it only evaluates the expression on the right if the one on the left is true.

So, this.options.pause == 'hover' && this.$element.on(... is a short-hand way of attaching the event listeners only if the pause option is set to 'hover' (because if it's not, the left-hand expression will be false, and the on functions won't be called).

Similarly, the final example you found only calls setInterval (and assigns the result to this.interval) if the desired interval is "true" (I imagine generally non-zero here, but also not undefined, etc.) and the carousel is not paused.

Post a Comment for "What's The Difference Between These Two Uses Of The && Logical Operator?"