Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does JavaScript have non-shortcircuiting boolean operators?

Tags:

In JavaScript

(f1() || f2()) 

won't execute f2 if f1 returns true which is usually a good thing except for when it isn't. Is there a version of || that doesn't short circuit?

Something like

var or = function(f, g){var a = f(); var b = g(); return a||b;} 
like image 213
Steven Noble Avatar asked Apr 13 '11 16:04

Steven Noble


People also ask

Which Boolean operators can be used in JavaScript?

There are three operators: AND, OR and NOT.

Does JavaScript have short circuit evaluation?

In JavaScript, short-circuiting is the evaluation of an expression from left to right with || and && operators. If the condition is met and the rest of the conditions won't affect the already evaluated result, the expression will short-circuit and return that result (value).

How is the NOT Boolean operator represented in JavaScript?

(NOT) The boolean NOT operator is represented with an exclamation sign ! . The syntax is pretty simple: result = !


2 Answers

Nope, JavaScript is not like Java and the only logical operators are the short-circuited

https://developer.mozilla.org/en/JavaScript/Reference/Operators/Logical_Operators

Maybe this could help you:

http://cdmckay.org/blog/2010/09/09/eager-boolean-operators-in-javascript/

| a     | b     | a && b | a * b     | a || b | a + b     | |-------|-------|--------|-----------|--------|-----------| | false | false | false  | 0         | false  | 0         | | false | true  | false  | 0         | true   | 1         | | true  | false | false  | 0         | true   | 1         | | true  | true  | true   | 1         | true   | 2         |  | a     | b     | a && b | !!(a * b) | a || b | !!(a + b) | |-------|-------|--------|-----------|--------|-----------| | false | false | false  | false     | false  | false     | | false | true  | false  | false     | true   | true      | | true  | false | false  | false     | true   | true      | | true  | true  | true   | true      | true   | true      | 

Basically (a && b) is short-circuiting while !!(a + b) is not and they produce the same value.

like image 170
Torres Avatar answered Oct 22 '22 23:10

Torres


You could use bit-wise OR as long as your functions return boolean values (or would that really matter?):

if (f1() | f2()) {     //... } 

I played with this here: http://jsfiddle.net/sadkinson/E9eWD/1/

like image 25
Sean Adkinson Avatar answered Oct 22 '22 21:10

Sean Adkinson