Reputation: 6240
In my project (browser context only) I want to use a JS code quality tool. I've tried both jslint
and eslint
. I want linter to help me make my code clean, clear, errorproof and improve its overall quality. What I don't want to do is I don't want to write some dirty hacks or use bad practices just to make linters happy.
I'm concerned about only one issue. Both of them reported a problem that I'm using a function before it was defined. Obviously in the following code snippet bar
won't be called before it's definition.
function foo() {
bar();
}
function bar() {
}
foo();
In this simplest scenario I can just move bar
before foo
. But there are cases when it's just impossible. First function uses the second, the second uses the third and the third uses the first.
It seems like I can make linters happy by declaring all functions before their definitions like this.
var foo;
var bar;
foo = function() {
bar();
};
bar = function() {
};
foo();
The questions are:
yes
I should stick to this practice, shouldn't I?no
what is the good practice regarding this issue?Upvotes: 12
Views: 157
Reputation: 2929
No, the snippets are not broken but not best practice either.
var foo = function(){
}
var bar = function(){
foo();
}
bar();
will actually become:
var foo, bar;
foo = function(){
}
bar = function(){
foo();
}
bar();
Hence you should define all variables and functions at the beginning of the scope. JavaScript uses Hoisting
which effectively moves all declarations for variables and functions to the top of the scope.
Doing it yourself is considered best practice and increases readability.
Eslint will check against the rule vars-on-top which is defined and documented here
https://www.reddit.com/r/learnjavascript/comments/3cq24a/crockford_says_hoisted_variable_declarations_are/ https://www.sitepoint.com/demystifying-javascript-variable-scope-hoisting/
Upvotes: 2
Reputation: 7621
Use strict mode always. "use strict"
have you functions inside scope like IIFE for not having global's variables
function foo() {
bar();
};
function bar() {
};
Upvotes: 1