27

I get the following error in jsLint:

'document' was used before it was defined.

Line that causes the error:

document.cookie = name + "=" + value + expires + "; path=/";

I get why this happens, but I would like my code to be compliant.

How do I resolve this?

Thanks.

Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132
starjava
  • 443
  • 2
  • 8
  • 14
  • If using jsLint in NetBeans IDE, there are options for assuming console, browser and nodeJS are available. Probably other IDEs have the same option. – kap Mar 24 '16 at 10:47

5 Answers5

50

Place

/*jslint browser:true */

in the beginning of the body of your function. Or, alternatively, you may use

/*global document: false */

JSLint is for the checking of any javascript code, and the document global object does not exists everywhere, so you have to manually tell JSLint that your code is aimed to be executed in browser, and thus document global variable is defined. For example, for server-side javascript it is expected for JSLint to report about this error.

Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132
penartur
  • 9,792
  • 5
  • 39
  • 50
2

From jslint's website, you can read about a /global/ directive that allows you to set variables that are assumed to be declared elsewhere.

Here is an example (put this at the top of the file):

/\*global var1,var2,var3,var4,var5\*/

or, in starjava's case:

/\*global document\*/

I'm not actually sure if the :true or :false is needed, but it looks like it's recommended from what I read on the site. http://www.jslint.com/lint.html

Make sure the initial global statement is on the same line as '/\*', or else it breaks.

Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132
stanton
  • 439
  • 5
  • 5
1

If all your JS code is supposed to be run from browser then just the add the --browser flag.

jslint --browser my.js
Kolyunya
  • 5,973
  • 7
  • 46
  • 81
0

if you are using node can add the following line

/ * node JSLint: true * /

at the start of the script http://jslinterrors.com/a-was-used-before-it-was-defined/

AURIGADL
  • 1,832
  • 2
  • 13
  • 15
0

In cli mode you can use config file:
jslint.conf

{
    "predef": [
        "module",
        "require",
        "window",
        "document",
        "jQuery",
        "Backbone",
        "Marionette",
        "Modernizr",
        "_",
        "setTimeout",
        "clearTimeout",
        "setInterval",
        "clearInterval"
    ],
    "evil":false,
    "indent":4,
    "vars":true,
    "passfail":false,
    "plusplus":false
}

And use jslint with --config jslint.conf parameter.

M Rostami
  • 4,035
  • 1
  • 35
  • 39