Why does ReSharper warn that a function is being used before it is declared?

I wrote JavaScript code with layout as below:

function MyObject() {
    this.doSomething(){
        someSubRoutine();
    }

    function someSubRoutine(){
        //Sub-routine code here
    }
}

      

ReSharper warns me that

The 'someSubRoutine' function is used before it is declared

It is true that the function is used before it is declared, but is there a real reason why ReSharper recommends that I declare my function before using it? I realized, due to JavaScript hoisting capabilities, this is not a problem. Should I follow this recommendation or should I just continue to ignore it?

+3


source to share


1 answer


ReSharper probably uses JSLint (or JSHint) under the hood, and these linting tools usually warn about this practice.

The problem boils down to a topic called "ascent" that has been discussed to a great extent (eg Sitepoint ). In some cases, it is possible to use a method or variable before the JS interpreter has the ability to declare it ... so the "best practice" is to declare somewhere above the first use.

Edit: Here's an example where hoisting can cause possible unintended side effects:



var showState = function() {
    console.log("Idle");
};

function showState() {
  console.log("Ready");
} 

showState();            // output: Idle

      

This is because the JS interpreter uses hoisting to create the following at runtime:

function showState(){        // moved to the top (function declaration)
    console.log("Ready");
} 

var showState;               // moved to the top (variable declaration)

showState = function(){      // left in place (variable assignment)
    console.log("Idle");
};

showState();

      

+5


source







All Articles