0

Consider the following code to exit a function early based on some condition.

function abc() {
  if (some_condition) {
    message('blah');
    return; // early exit
  }
  // otherwise do stuff
}

Coming here to pose this question I found Mehdi's answer in this post is essentially where I'm at jquery javascript avoid running function on condition

However I'd like to modularise the condition so I can use it in a number of places, and the best I've gotten is this (I'm a long time PL/SQL programmer, which may show as I understand this event based world)

function check_condition() {
  if (some_condition) {
    message('blah');
    return false; // early exit
  }
  else
    return true;
}

function abc() {
  if (!check_condition()) {return;}

  // otherwise do stuff
}

In reading articles such as this I realise that there is possibly a grander scheme of not entering the function in the first place, but I wonder if there is a tidier way to propagate the message out of check_condition() to exit early from abc()

I still feel that I'm repeating just as much code with the (!check_condition()) call.

Cheers

Community
  • 1
  • 1
Scott
  • 4,857
  • 3
  • 22
  • 33

1 Answers1

1

The stuff you do in abc can be coded in a function executed only when checkCondition is true, e.g.

function checkConditionAndExecute(fn) {
  if ( some condition ) {
    fn();
  }
}


function abc() {
  checkConditionAndExecute(function () {
    // this is only executed when some condition is true :)
  });
}
Mauricio Poppe
  • 4,817
  • 1
  • 22
  • 30