Kolyunya
Kolyunya

Reputation: 6240

Defining JavaScript functions

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:

Upvotes: 12

Views: 157

Answers (2)

Tim Hallyburton
Tim Hallyburton

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

Jorawar Singh
Jorawar Singh

Reputation: 7621

  1. Is the first code snippet broken? no it's not broken.
  2. Is the first code snippet error-prone? No.
  3. Is it a good practice to organize code like the second snippet (declare functions before defining them)? NO there are many other good ways
  4. If yes I should stick to this practice, shouldn't I? Yes
  5. If not what is the good practice regarding this issue? there are many good pattern you can follow
  6. Is this linter error worth paying attention to or should I just disable it? It's good to pay attention for keep your code clean

Use strict mode always. "use strict"

have you functions inside scope like IIFE for not having global's variables

read more about IIFE

function foo() {
    bar();
};

function bar() {

};

Upvotes: 1

Related Questions