24

Why does JSLint complain if something uses a function that hasn't been defined already? The point is that the function is defined -- and if that something calls that function, that function exists and things will work.

Take a look at the code below:

function foo()
{
   // calls bar()
};

function bar()
{
   // calls foo()
};

There is no way to organize the 2 methods in such a way that it would make JSLint happy. How do I deal with this issue?

StackOverflowNewbie
  • 39,403
  • 111
  • 277
  • 441

3 Answers3

19

JSLint can't deal with this as far as I know, but JSHint, based on JSLint, tackles this problem in a proper manner.

Just use the "latedef" property and set it to "false". In case you nevertheless want to detect these kind of problematic variable definitions, but do want to use function expressions and allow hoisting of these functions, you can set "latedef" : "nofunc".

Check it out here.

  • One note - "nofunc" value for "latedef" option helps to avoid the inspection for function declarations (not expressions). – Alexey Sep 22 '14 at 05:45
14

See this answer:

Contending with JS "used before defined" and Titanium Developer

Basically, if you use the foo = function() { ... } form, you can declare var foo, bar; at the top to avoid the JSLint errors.

Community
  • 1
  • 1
MrTrick
  • 1,927
  • 12
  • 11
  • 6
    But that just a tiny bit different from `function foo()`, being function expression and all. Plus, declaring `var foo, bar` at the top is superfluous due to hoisting. So, in short, `var foo = function()...,var bar = function()...` will do just fine technically. Additionally, I think, considering that function declarations are loaded before anything else - JSLint should fix their stuff already. – ZenMaster Sep 15 '11 at 03:36
  • 10
    @ZenMaster: A fork of `jslint`, [`jsHint`](http://www.jshint.com/docs/), solved this be letting you set `"latedef" : false` in the options. (It does not affect variable names, just function names.) – dgo.a Nov 14 '12 at 09:43
  • 1
    This answer will break code that relies on function definition hoisting~ – Riley Lark Sep 19 '13 at 13:47
0

I have just dealt with a problem that was very similar to this and the problem was my script was in place after the function call,

function zzzzz () {
   aaaaa();
   ccccc();
  }

function aaaaa() {
 blah = bla blah blah;
 }
function bbbbb() {
 blah = bla blah blah;
 }
function ccccc() {
 blah = bla blah blah;
 }

so i placed the function call after the script and it cured the problem, so basic i couldn't see the answer for days sorted now, so give it a try

function aaaaa() {
 blah = bla blah blah;
 }
function bbbbb() {
 blah = bla blah blah;
 }
function ccccc() {
 blah = bla blah blah;
 }

function zzzzz () {
   aaaaa();
   ccccc();
  }

Goood Luck and i hope this helps

Morph
  • 9
  • 2