0

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?

Marcus Hughes
  • 1,147
  • 2
  • 14
  • 21

1 Answers1

1

I'd go with version 1 as it's more readable. You see that it handles 2 cases and what more clearly, one of them being a string the other an element directly. I have never seen a check against instanceof String though, as to my experience in 99% people declare string primitives. I tested gEBI a bit and it seems quite robust, it'll just return null for anything invalid (arrays, functions, objects, ...).

As to check whether elem actually is an HTML element see this: JavaScript isDOM -- How do you check if a JavaScript Object is a DOM Object?

Community
  • 1
  • 1
christian314159
  • 639
  • 3
  • 6