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?
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With