Reputation: 4583
I'm reviewing some code where the logic looks flawed. I'm not sure if the following code will ever return false because of the if else return flow. My question is, will the following code ever return false, or even throw an error?
function performSearch(e) {
if(e.keyCode === RETURN_KEY_KEYCODE) {
var select = document.getElementById("selectmenusearch");
var selected = select.options[select.selectedIndex].value;
if(selected === 'organisation') {
submitSearchForm('<%= doOrganisationSearchURL %>');
} else {
submitSearchForm('<%= doIndividualSearchURL %>');
}
} else {
return false;
}
return true;
}
So the flow to me looks like
if (this condition is true) {
//execute some code
} else {
return false
}
else return true
NB: I know it would be better to refactor to have only one return statement but it looks to me like there are two else
statements.
Upvotes: 0
Views: 61
Reputation: 721
It depend of e.keyCode but if e.keyCode is not always equal to RETURN_KEY_CODE it will not always return false. You have 2 return. The first one is in the else of the first if so if e.keyCode !== RETURN_KEY_CODE, false is return. Else, you if will end normally and the instruction after it is return true.
function performSearch(e) {
if(e.keyCode === RETURN_KEY_KEYCODE) {
...
} else {
return false; // RETURN_KEY_KEYCODE !== e.keyCode
}
return true; // RETURN_KEY_KEYCODE === e.keyCode
}
I don't see any wait it can alway return false if e.keyCode is not always the same value. :)
If you want to make it more clear, you can just put the return in the end of the first if. Like that:
function performSearch(e) {
if(e.keyCode === RETURN_KEY_KEYCODE) {
...
return true; // RETURN_KEY_KEYCODE === e.keyCode
} else {
return false; // RETURN_KEY_KEYCODE !== e.keyCode
}
}
Upvotes: 1
Reputation: 11408
Just run a test. Seems like you were confused with what happens when there is more than one "return" statement in a function.
A return statement is a regular statement, just like any other - except for the fact that it will interrupt the local block execution and return flow control to the code that called the function. It is indifferent for you the fact that you have one, two, three returns... the language interpreter strictly follows the IF/ELSE rules - if a condition is met, then the block (delimited with "{ }" defined immediately under the if is the one that is executed, if the condition is not met, then the respective if's else block is executed. Whatever is the case, both if and else blocks, upon reaching their ends, will return flow to the next statement right after the if block (the if block is comprised by the if + else blocks), in the example here, "return true".
(function() {
if (k) {
console('k renders true');
}
else {
console.log('else reached');
return false;
}
return true;
console.log('bottom return true reached');
})();
Upvotes: 1