Search code examples
javascriptjqueryundefined-function

Uncaught TypeError: areFieldsSet is not a function


I have my JS code as :

    $(function () { //line-1
     if(window.location.search.length >1){
    //doSomething ;
     areFieldsSet(); //call this function
    } //end of if 

    var areFieldsSet = function(){
    //do something
    }
    //do many things
   } // end of line-1 function

Now, I am getting an error when I am trying to refer areFieldsSet function as described in the question title. Where am I going wrong ?


Solution

  • The problem is that you are defining the function after calling it.

    JavaScript does something called "hoisting". Take a look at this article: Variable and Function Hoisting in JavaScript

    The rules can sometimes be confusing, but basically function definitions using the function x() notation are implicitly moved to the top, and variable definitions are moved as well, but not their initialization!

    For example, var x = 5; somewhere further down will work as if var x; was written at the start of your code block/function, but x = 5; further down. So x will be defined before the assignment, but with a value of undefined.

    So, you have two options: Either you move your areFieldsSet function above the place where you call it, or you change it from var areFieldsSet = function() to just function areFieldsSet() which will make it eligible to function hoisting (and not just variable hoisting).