1
function getOrInsertEmptyElemById(id){
    var elem = $(id) || document.body.insert('<div id="'+id+'"></div>');
    return elem;
}

I find myself using functions like the above quite often. But I struggle on naming them.
How is a make sure it exists and return function usually named?

3

It's a guard or a guard function. The idea is that checks to make sure that some condition is true and then either continues or aborts the branching condition. It can also be regarded as a kind of filter function.

This should not to be confused with guards as they are used in Haskell and other functional style programming languages, which operate more like switches.

You might consider naming it as "NullGuard" or "NullFilter". "NullCatcher" might also be good as this pattern is also somewhat similar to the often more familiar "try, catch, finally" pattern of exception handling.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.