I recently realized that when I use a function to loop over an array and return a match, I actually don't need the return false/null at the end.
For example, if I have:
*Edited example. Original example was from a function I tried to simplify but forgot to change the name/context of. Sorry for the confusion. Here is a better example fitting the title of my question:
var hasKey = hasKeyMatch(key);
function hasKeyMatch(key) {
for (var i = 0; i < array.length) {
if (array[i].key === key) {
return true;
}
}
};
I don't actually need a return false, as if there is no return of key, hasKey will be undefined. So I can still use hasKey as a boolean.
But is this considered good style? I realize having a 'back-up' return is a necessity in languages like Java, and so some people bring the habit to JS. But I think minimizing unnecessary returns would be ideal, though I have no idea of the actual cost of returning.
And I when I look at the answer to the below question, I am confused on why he chooses to return a variable that is already pushed to the desired array. I assume his return is intentional, and he isn't intended to store the returned variable anywhere. Are there benefits (like say garbage collection) of returning a variable at the end of a function?