-1

Is possible to break execution program from function or I need to check boolean val returned?

Code

function check(something) {

    if (!something) return;
    // Else pass and program continuing
}

check(false); // I want to stop execution because function has returned
// Or I need to check value like if (!check(false)) return; ?
// I want easiest possible without re-check value of function..

alert("hello");
Davide
  • 475
  • 4
  • 19

3 Answers3

1

One way would be to through an Error, but otherwise you would need to use a boolean check, yes. I would recommend to use the boolean

function check(something) {

    if (!something) throw "";
    // Else pass and program continuing
}

check(false); // I want to stop execution because function has returned
// Or I need to check value like if (!check(false)) return; ?
// I want easiest possible without re-check value of function..

alert("hello");
CoderPi
  • 12,985
  • 4
  • 34
  • 62
0

Easiest...

(function(){
  function check(something) {

    if (!something) return false;
    // Else pass and program continuing
  }

  if(!check(false)) return; 

  alert("hello");
});

(function(){ ... }); is called IIFE Immediately-invoked function expression.

void
  • 36,090
  • 8
  • 62
  • 107
0

Put your code in an IIFE, then you can use return

(function() {
    function check(something) {
        if (!something) {
            return false;
        } else {
            return true;
        }
    }

    if (!check(false)) {
        return;
    }

    alert("hello");
});
Barmar
  • 741,623
  • 53
  • 500
  • 612