Logo
23 Nov 2012 | 1 min. (110 words)

Check javascript function exists before calling it

On large applications, there may be some instances where you need to make a call to a function which belongs in a different javascript file.

There might also be a case where this javascript file isn’t always included on every page, and should only be called if it is included.

If we are to call this function, and it hasn’t been included, a javascript error will be returned.

Therefore we need to first check that the functions exists in the current context. Using typeof we can determine whether the browser detects the function name as a function, and run it only if it exists:

if (typeof(foo) === 'function'){
    foo();
}
function javascript
Twitter Facebook Google+

Reading URL hashtag values

…

Creating a new rule for a CSS class in jQuery

…

Related Links

  • LinkedIn
  • Twitter
  • Stack Overflow
  • GitHub

Stack Exchange

profile for Curt on Stack Exchange, a network of free, community-driven Q&A sites
Follow @curtistimson

Recent Posts

  • Adding a body class in GatsbyJs to prevent flashing content
  • ReactJs Snapshot unit testing and mocking components
  • Access user details and email address from Auth0 with NodeJs
  • Hosting Hugo on Netlify
  • Dopetrope Hugo Theme
Theme Bleak by zutrinken Published with Hugo
Menu