Often times when I'm writing my JavaScript code I can't shake the paranoia that some function or line of code is going to break in this browser or that...
How can I check to see if the code I'm writing is x-browser compatible?
Basic feature detection can be done by querying window properties, eg window.XMLHttpRequest.
In certain cases it becomes a lot more complex than just querying properties, since methods defined can be inconsistent with one another. In that case it really depends on the scenario but certain times you may need to do something as dirty as creating an element that's offset from the screen, then set certain properties and see if those changes reflected or not.
It would probably be useful if you specifically gave examples of certain cases, as there are literally thousands of things to feature detect for and not everything is the same.
You can check if the function for the feature you want to use exists like this:
if(functionOrObjectName) {
//will execute if the function or object is defined
}
typeof undefinedVar will return 'undefined' for undefined vars and functions. What you suggest does work if you are testing for a property. So to test for global functions and vars (which are props of the window object) you can use if (window.undefinedVar) which will not cause an errorYou might find this test/compatibility table site handy: http://robertnyman.com/javascript/ .
Check out has.js too. It should simplify feature detection a bit.
const, getters, and the like. But I think you mean DOM and BOM features, likedocument.activeElement, which people have given you a few clues. But there isn't one answer for all your needs. The basic idea is feature detection (ejohn.org/blog/future-proofing-javascript-libraries) over browser detection. However, this won't tell you about bugs in features, only that they are implemented.