Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have written JavaScript code with a layout as seen below:

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

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

ReSharper warns me that

Function 'someSubRoutine' is used before it is declared

It is true that the function is used before it is declared, but is there an actual reason ReSharper is recommending I declare my function prior to usage? I figured due to JavaScript's hoisting abilities, this wouldn't be a problem. Should I be following this recommendation or just continue ignoring it?

like image 801
puddinman13 Avatar asked Jun 30 '15 14:06

puddinman13


1 Answers

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

The issue boils down to a topic called "hoisting", which has been discussed heavily (for example, Sitepoint). It's possible in some cases to use a method or variable before the JS interpreter has a chance to declare it... so the "best practice" is to declare somewhere above the first use.

Edit: Here is an example where hoisting will 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 during 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();
like image 161
arthurakay Avatar answered Nov 14 '22 22:11

arthurakay