2

Recently, I have noticed, that putting an or operator between two functions, will make the second one run only if the first side of the operator is false. Is it safe to use this instead of if statements?

Example:

function a(){ return Math.random() >= 0.5; } 
function b(){ console.log("foo"); }

Using

!a() || b();

has the same behaviour as

if( a() ) b();

My question is: Is it safe to use this syntax? Are there exceptions?

István Pálinkás
  • 2,217
  • 7
  • 25
  • 50

1 Answers1

8

Yes, it is safe to rely on this (although the readability is open to debate and depends on the exact use case).

This behaviour is called "short-circuit evaluation", and is a feature of many programming languages. See Does JavaScript have "Short-circuit" evaluation?

Community
  • 1
  • 1
NPE
  • 486,780
  • 108
  • 951
  • 1,012