DUMBUSER
DUMBUSER

Reputation: 531

how to stop the execution of code in node js other than return

so i want to stop the code when a certain event happens but dont want to use return since the function is supposed to return a value and if i use it to stop the code it would reutnr an undefined value for example this what i need

  foo =() =>{
     if(event){
        //stop code 
    }else {
    return "Value"
    
    }

}

what i dont want to do

    bar =() =>{
    if(event){
    // dont want to use it since it would return an undefined value 
     return ;
    }else{
    
    return "Value" ; 
    }

}

Upvotes: 1

Views: 687

Answers (1)

But why would you not want undefined to be returned? I mean... even if you have a function that returns no value at all it would still return undefined.

const a = (function(){})();
console.log(a); // undefined

This is just default behaviour of javascript. However, if you wish to stop execution due to a certain condition my best suggestion to you is to throw an exception and handle it.

const MyFunction = (b) => {
  if (b) throw 'You shall not pass!';

  return 'I shall pass! This time...';
};

try {
  console.log(MyFunction(false));
 console.log(MyFunction(true));
} catch(err) {
  console.log(err);
}

Upvotes: 1

Related Questions