1

var cost = function () {

  if (x.value == "1") {
   ....
  } else if (x.value == ""){
     I want my program to stop the execution of any further code here if x.value = empty or null
  }
};

I tried to return false here.

  • New to programming
  • Just add a `return;` statement. How are you using `cost`? Also, change your `else if ( etc )` to just `else`. – Dai Mar 05 '22 at 02:59
  • Perhaps a duplicate of https://stackoverflow.com/a/9298915/3196753. – tresf Mar 05 '22 at 03:37

3 Answers3

1
  var cost = function () {
  if(!x) return;
  // do rest of stuff that is necessary if x isn't null | empty
};
Muhammad Atif Akram
  • 1,204
  • 1
  • 4
  • 12
  • Please read "[answer]". It helps more if you supply an explanation why this is the preferred solution and explain how it works. We want to educate, not just provide code. – the Tin Man Mar 11 '22 at 05:55
1

To stop the execution of function simply return

if (x.value == "1") {
   ...
  } else if (!x.value){
     return;
  }
};
mow
  • 58
  • 1
  • 7
1

A closed scope of functionality should be enclosed in a function, to be controlled the way you want.

When inside of a function, you can decide when the program ends by using the word return.

The "return" keyword is usually used to make your function return something to its caller, but that's not mandatory, so using it alone, without a specific thing being returned, is ok.

var cost = function (someParameter) {

  if (someParameter==='some value') {
   return; // It's returning 'undefined' here, and the function is stopping
  } 
  const a = 1;
  const b = 1;
  return a + b;
};

Not, it's important to notice that, except for a NodeJS driven Javascript program, you can't stop the whole javascript outside that function scope.

Javascript, as many languages, is based on scope levels, meaning that you can only control what's inside your scope, not outside.

If you need the logic outside that function to be stope, also, you should have another function scope behind it.

Example:


const functionA = function(paramX){
    if(paramX==='foo'){
       return true;
    }
     else {
       return false;
    }
    // this whole thing could be a ternary, though like:
    //  return paramX==='foo' 
}


// This one is the one that has the most upper level in the scope chain
const functionB = function(){
    let a = 1,
        b = 2,
        c = 3;

    // Negating the function return
    // so if the functionA returns false,
    // my functionB won't continue execution
    if(!functionA(a+b+c===5)){
        return;
    }

    // Now your code can continue to it's purpose because
    // functionA returned true
    // ...


}

Guilherme Ferreira
  • 2,209
  • 21
  • 23
Hritik Sharma
  • 1,756
  • 7
  • 24