I have been going through some of my old code, and a lot of it employed snippets I grabbed online. I ran across a couple such borrowed functions that require an element as an argument, but this element can be passed in either as the element itself, or as a string to be used in .getElementById()
. Which of the below two is better, and why? Or is there an even better version? (Better = readable, standard, safe)
Version 1
function doSomethingWithElem( elem /*, param2, ... */ ) {
elem = (typeof elem === 'string' || elem instanceof String)
? document.getElementById( elem )
: elem;
// more stuff...
}
Version 2
function doSomething2( elem /*, param2, ... */ ) {
elem = document.getElementById( elem ) || elem;
// more stuff...
}
The primary difference being that one checks for an instance of string before calling gEBI, whereas the other relies on gEBI returning undefined
. Neither of them checks to make sure elem
is indeed an HTMLElement
.
Assuming a well-defined API (the user knows he should pass in a string or HTML element), how important is type-checking? Is type-checking primarily needed to help users of your scripts to debug their own code? Are there subtle pitfalls of either of these, such as possible return values of gEBI that could mess up version 2?