I am using a function to check if required fields are filled. I have these two functions, that should do the same, however the first one does not. Shouldn’t javascript stop executing code, after it meets a return?
This functions returns true:
//Checks if various stages are ready
function trnReady(area) {
switch (area)
{
case 'settings':
$('input.required').each(function(){
if($(this).val() == '')
{
return false;
}
});
break;
}
return true;
}
While this one returns false:
//Checks if various stages are ready
function trnReady(area) {
var r = true;
switch (area)
{
case 'settings':
$('input.required').each(function(){
if($(this).val() == '')
{
r = false;
}
});
break;
}
return r;
}
I thought the first return would stop executing code? I’m wondering if it has anything to do with scope?
In first code snippet
return false;stops execution only of inner function passed to jquery each method. Also it stops jquery iteration accordingly to jquery API. But in any case trnReady returns true.Second code snippet is correct, but you can optimise it, replacing
r = false;toreturn r = false;(it will stop iteration by jquery when you already know that one of fields isn’t filled)