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?
drawImage using toDataURL of an html5 canvas
This is a matter of code solidity and you should always return false instead of undefined if the method name suggest that as a result.
As everything which has to do with code style it is not a matter of right or wrong (http://www.youtube.com/watch?v=zN-GGeNPQEg) but it is important if you intent others to understand what you are doing and avoiding stupid bugs. Solid code avoids the possibility of doing stupid things by behaving as expected.
For example: isA() && isB() || !isA() && !isB() can be written more shortly as isA() == isB().
If you had these two functions defined as one (isA) returning false and one (isB) returning undefined the second expression would not behave as one might suspect.
See: http://jsfiddle.net/wDKPd/1/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With