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
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.
var cost = function () {
if(!x) return;
// do rest of stuff that is necessary if x isn't null | empty
};
To stop the execution of function simply return
if (x.value == "1") {
...
} else if (!x.value){
return;
}
};
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
// ...
}