Search code examples
javascriptundefined

Test for undefined function in Javascript


So Safari keeps yelling at me for one specific error.

I'm trying to use Google Maps API and call map.getCenter();. However sometimes, this happens before the map has been fully loaded.

So instead in my function I test for an undefined call like this:

if (map.getCenter() != undefined)

But that still errors out because I guess it doesn't even like making the call just to test the if the result is undefined or not?

Can I get some help here?

Thanks!


Solution

  • if (typeof map !== 'undefined' && map.getCenter) {
       // code for both map and map.getCenter exists
    } else {
      // if they dont exist
    }
    

    This is the right way to check for existence of a function.. Calling the function to test its existence will result in an error.

    UPDATE: Snippet updated.