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

Reading URL hashtag values

…

Creating a new rule for a CSS class in jQuery

…

Related Links

  • LinkedIn
  • Twitter: @curtcode
  • Stack Overflow
  • GitHub: @curtiscde

Stack Exchange

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

Recent Posts

  • My terminal setup and commands I use on a daily basis when working with GitHub
  • Displaying latest posts on your GitHub profile
  • Using Codecov within a monorepo
  • Displaying Strava stats using webhooks & GitHub Actions
  • Filtering duplicate data points on Chart.js
Theme Bleak by zutrinken Published with Hugo
Menu