Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does JSLint complain about undefined/implied global variable?

I'm trying to understand why JSLint complains about an implied global variable in the following example:

var TEST = (function () {
  var count = 0;

  function get_count() { 
    return add_one(); 
  }

  function add_one() {
    count += 1;
    return count;
  }

  return { 
    get_count: get_count
  };
}());

Running this through JSLint gives the error:

Problem at line 5 character 12: 'add_one' is not defined.

As well as saying:

Implied global: add_one 5

If you move the add_one() function before the get_count() function the error goes away. However with the code as it is above, it doesn't produce any errors when you run it in the browser. Can anyone explain why JSLint is complaining?

Thanks!
Matt

like image 834
m4olivei Avatar asked Dec 12 '22 18:12

m4olivei


1 Answers

This is because JSLint uses a Pratt Parser, a top-down parser, not a full-blown JavaScript interpreter. If it were truly interpreted, then it wouldn't give you that error.

add_one is an implied global because the parser didn't come across that variable yet, so it assumes that your surrounding code will have that variable. But, if you flip it around, then the parser has already came across the add_one variable and it's all peaches and cream :-)

By the way, I noticed a small typo in your closing function line: }()); should be })();.

like image 133
Jacob Relkin Avatar answered Feb 09 '23 00:02

Jacob Relkin