Bryant11
Bryant11

Reputation: 333

JavaScript if statement optimization

I have the following code:

      function() {
         if (foo && foo.bar !== baz) { //needed because foo can be undefined, so foo.bar always returns value
            function1()
            return;
         }

         if (foo) {
            function2()
         } else {
            function1()
         }
      }

I was wondering, what would be the best way to optimize these if statements, from code structure point of view.

Thanks for all the answers!

Upvotes: 1

Views: 85

Answers (4)

Aadit M Shah
Aadit M Shah

Reputation: 74204

This can be converted into a one-liner:

foo && foo.baz === baz ? function2() : function1();

If foo is falsey then it will execute function1 and if foo is truthy but foo.baz !== baz then it will still execute function1. Otherwise, it will execute function2.

The reason this works is because if foo is truthy and foo.baz !== baz is false then function2 is only executed if foo.baz === baz is true.

Upvotes: 1

rslite
rslite

Reputation: 84673

An example could be:

if (!foo || foo.bar !== baz) {
  function1();
} else {
  function2();
}

Similar to kamituel's one, but shorter, and maybe easier to read.

Upvotes: 1

void
void

Reputation: 36703

((foo && foo.bar !== baz) || !foo) ? funtion1() : function2());

Upvotes: 1

kamituel
kamituel

Reputation: 35950

Might be:

if ((foo && foo.bar !== baz) || !foo) {
  function1();
} else {
  function2();
}

Upvotes: 1

Related Questions