Check whether function exists

Tags: jQuery, JavaScript

It is always a best practice to check whether a function exists before calling it using JavaScript or jQuery. The following code snippets show how we can check whether a function exists using JavaScript and jQuery.

JavaScript

<script type="text/javascript">
    function doSomething() {
    }
 
   if (window.doSomething)
        document.writeln("Function exists");
    else
        document.writeln("Function does not exists");
</script>

The above code creates a function named doSomething and then uses window element to check whether the function exists and writes to document depending on the validation. You get the output as "Function exists".

jQuery

You can use isFunction(parameter) method of jQuery to find out whether the passed parameter is a function or not.

<script type="text/javascript">
    function doSomething() {
    }

    //jQuery
    if ($.isFunction(window.doSomething))
        document.writeln("Function exists");
    else
        document.writeln("Function does not exists");
</script>

The output remains the same as "Function exists" as the function exists.

Add a Comment