JSHint

  * About
  * Docs
  * Install
  * Hack
  * Blog

Contents

  * Usage
  * JSHint as a JavaScript library
  * Configuring JSHint from within JavaScript files
  * JSHint options
  * Still confused?

Usage

The easiest way to use JSHint is to install it as a Node program. To do so,
simply run the following command in your terminal (flag -g installs JSHint
globally on your system, omit it if you want to install JSHint in the current
working directory):

$ npm install jshint -g

After you?ve done that you should be able to use the jshint program. The
simplest use case would be linting a single file or all JavaScript files in a
directory:

$ jshint myfile.js
myfile.js: line 10, col 39, Octal literals are not allowed in strict mode.

1 error

JSHint comes with a default set of warnings but it was designed to be very
configurable. There are two main ways to configure your copy of JSHint before:
you can either specify the configuration file manually via the --config flag or
use a special file .jshintrc. JSHint will look for this file in the current
working directory and, if not found, will move one level up the directory tree
all the way up to the filesystem root.

This setup allows you to have different configuration files per project. Place
your file into the project root directory and, as long as you run JSHint from
anywhere within your project directory tree, the same configuration file will
be used.

Configuration file is a simple JSON file that specifies which JSHint options to
turn on or off. For example, the following file will enable warnings about
undefined and unused variables and tell JSHint about a global variable named
MY_GLOBAL.

{
  "undef": true,
  "unused": true,
  "globals": { "MY_GLOBAL": false }
}

Other configuration flags supported by JSHint:

  * --reporter Allows you to modify JSHint?s output by replacing its default
    output function with your own implementation.

    $ jshint --reporter=myreporter.js myfile.js

    This flag also supports two pre-defined reporters: jslint, to make output
    compatible with JSLint, and checkstyle, to make output compatible with
    CheckStyle XML.

    $ jshint --reporter=checkstyle myfile.js
    <?xml version="1.0" encoding="utf-8"?>
    <checkstyle version="4.3">
            <file name="myfile.js">
        <error line="10" column="39" severity="error"
          message="Octal literals are not allowed in strict mode."/>
      </file>
    </checkstyle>

    See also: Writing your own JSHint reporter.

  * --verbose Adds message codes to the JSHint output.

  * --show-non-errors Shows additional data generated by JSHint.

    $ jshint --show-non-errors myfile.js
    myfile.js: line 10, col 39, Octal literals are not allowed in strict mode.

    1 error

    myfile.js:
      Unused variables:
        foo, bar

  * --extra-ext Allows you to specify additional file extensions to check
    (default is .js).

  * --help Shows a nice little help message similar to what you?re reading
    right now.

  * --version Shows the installed version of JSHint.

Rhino

JSHint also has a Rhino build which you can download here.

$ rhino jshint-rhino.js myfile.js

Note that Rhino version doesn?t support flags described above. It is, actually,
pretty basic.

Ignoring files

If you want JSHint to skip some files you can list them in a file named
.jshintignore. For example:

legacy.js
somelib/**
otherlib/*.js

Hooking up into the file resolution logic

The CLI JSHint module exposes a public method gather that you can use to hook
up into the file resolution logic. This is useful if you want to change how
JSHint gathers files for linting. Do this only if you really know what you?re
doing.

#!/usr/bin/env node

var cli = require("./src/cli/cli.js");

cli.gather = function (opts) {
  // Your own file gathering logic.
  // For description of 'opts' see src/cli/cli.js:gather
};

cli.interpret(process.argv);

JSHint as a JavaScript library

You can also use JSHint in your projects as a JavaScript library. You can
either install it as a Node module and include with require or download our web
bundle which exposes a global JSHINT function.

// With Node
var JSHINT = require("jshint").JSHINT;

JSHINT is a function that takes three formal parameters and returns a boolean:

var success = JSHINT(source, options, globals);

The first parameter is either a string or an array of strings. If it is a
string, it will be split on ?\n? or ?\r?. If it is an array of strings, it is
assumed that each string represents one line. The source can be JavaScript or
JSON.

The second parameter is an optional object of options which control the
operation of JSHINT. Most of the options are booleans: They are all optional
and have a default value of false.

The third parameter is an object of global variables, with keys as names and a
boolean value to determine if they are assignable.

If your input passes JSHint tests, the function will return true. Otherwise, it
will return false. In that case, you can use JSHINT.errors to retrieve the
errors or request a complete report by calling the JSHINT.data() method.

Configuring JSHint from within JavaScript files

In addition to the --config flag and .jshintrc file you can configure JSHint
from within your files using special comments. These comments start either with
jshint or global and are followed by a comma-separated list of value. For
example, the following snippet will enable warnings about undefined and unused
variables and tell JSHint about a global variable named MY_GLOBAL.

/* jshint undef: true, unused: true */
/* global MY_GLOBAL */

You can use both multi- and single-line comments to configure JSHint. These
comments are function scoped meaning that if you put them inside a function
they will affect only this function?s code.

Directives

         A directive for setting JSHint options.
jshint
         /* jshint strict: true */

         A directive for setting JSHint-compatible JSLint options.
jslint
         /* jslint vars: true */

         A directive for telling JSHint about global variables that are defined
         elsewhere. If value is false (default), JSHint will consider that
         variable as read-only. Use it together with the undef option.

         /* global MY_LIB: false */
globals
         You can also blacklist certain global variables to make sure they are
         not used anywhere in the current file.

         /* global -BAD_LIB */

         A directive for telling JSHint about global variables that are defined
         in the current file but used elsewhere. Use it together with the
exported unused option.

         /* exported EXPORTED_LIB */

         A directive for telling JSHint about all properties you intend to use.
members  This directive is deprecated.


JSHint options

Most often, when you need to tune JSHint to your own taste, all you need to do
is to find an appropriate option. Trying to figure out how JSHint options work
can be confusing and frustrating (and we?re working on fixing that!) so please
read the following couple of paragraphs carefully.

JSHint has two types of options: enforcing and relaxing. The former are used to
make JSHint more strict while the latter are used to suppress some warnings.
Take the following code as an example:

function main(a, b) {
  return a == null;
}

This code will produce the following warning when run with default JSHint
options:

line 2, col 14, Use '===' to compare with 'null'.

Let?s say that you know what you?re doing and want to disable the produced
warning but, in the same time, you?re curious whether you have any variables
that were defined but never used. What you need to do, in this case, is to
enable two options: one relaxing that will suppress the === null warning and
one enforcing that will enable checks for unused variables. In your case these
options are unused and eqnull.

/*jshint unused:true, eqnull:true */
function main(a, b) {
  return a == null;
}

After that, JSHint will produce the following warning while linting this
example code:

demo.js: line 2, col 14, 'main' is defined but never used.
demo.js: line 2, col 19, 'b' is defined but never used.

Sometimes JSHint doesn?t have an appropriate option that disables some
particular warning. In this case you can use jshint directive to disable
warnings by their code. Let?s say that you have a file that was created by
combining multiple different files into one:

"use strict";
/* ... */

// From another file
function b() {
  "use strict";
  /* ... */
}

This code will trigger a warning about an unnecessary directive in function b.
JSHint sees that there?s already a global ?use strict? directive and informs
you that all other directives are redundant. But you don?t want to strip out
these directives since the file was auto-generated. The solution is to run
JSHint with a flag --verbose and note the warning code (W034 in this case):

$ jshint --verbose myfile.js
myfile.js: line 6, col 3, Unnecessary directive "use strict". (W034)

Then, to hide this warning, just add the following snippet to your file:

/* jshint -W034 */

A couple things to note:

 1. This syntax works only with warnings (code starts with W), it doesn?t work
    with errors (code starts with E).
 2. This syntax will disable all warnings with this code. Some warnings are
    more generic than others so be cautious.

Enforcing options

              This option prohibits the use of bitwise operators such as ^ (XOR), | (OR)
bitwise       and others. Bitwise operators are very rare in JavaScript programs and quite
              often & is simply a mistyped &&.

              This option allows you to force all variable names to use either camelCase
camelcase     style or UPPER_CASE with underscores.

              This option requires you to always put curly braces around blocks in loops
              and conditionals. JavaScript allows you to omit curly braces when the block
              consists of only one statement, for example:

              while (day)
                shuffle();
curly
              However, in some circumstances, it can lead to bugs (you'd think that sleep()
              is a part of the loop while in reality it is not):

              while (day)
                shuffle();
                sleep();

              This options prohibits the use of == and != in favor of === and !==. The
              former try to coerce values before comparing them which can lead to some
eqeqeq        unexpected results. The latter don't do any coercion so they are generally
              safer. If you would like to learn more about type coercion in JavaScript, we
              recommend Truth, Equality and JavaScript by Angus Croll.

              This option tells JSHint that your code needs to adhere to ECMAScript 3
              specification. Use this option if you need your program to be executable in
es3           older browsersâ  such as Internet Explorer 6/7/8â  and other legacy
              JavaScript environments.

              This option requires all for in loops to filter object's items. The for in
              statement allows for looping through the names of all of the properties of an
              object including those inherited throught the prototype chain. This behavior
              can lead to unexpected items in your object so it is generally safer to
              always filter inherited properties out as shown in the example:

              for (key in obj) {
forin           if (obj.hasOwnProperty(key)) {
                  // We are sure that obj[key] belongs to the object and was not inherited.
                }
              }

              For more in-depth understanding of for in loops in JavaScript, read Exploring
              JavaScript for-in loops by Angus Croll.

              This option prohibits the use of immediate function invocations without
              wrapping them in parentheses. Wrapping parentheses assists readers of your
immed         code in understanding that the expression is the result of a function, and
              not the function itself.

              This option enforces specific tab width for your code. For example, the
              following code will trigger a warning on line 4:

              /*jshint indent:4 */
indent
              if (cond) {
                doSomething(); // We used only two spaces for indentation here
              }

              This option prohibits the use of a variable before it was defined. JavaScript
              has function scope only and, in addition to that, all variables are always
              movedâ  or hoistedâ   to the top of the function. This behavior can lead to
              some very nasty bugs and that's why it is safer to always use variable only
latedef       after they have been explicitly defined.

              For more in-depth understanding of scoping and hoisting in JavaScript, read
              JavaScript Scoping and Hoisting by Ben Cherry.

              This option requires you to capitalize names of constructor functions.
              Capitalizing functions that are intended to be used with new operator is just
              a convention that helps programmers to visually distinguish constructor
              functions from other types of functions to help spot mistakes when using
              this.
newcap
              Not doing so won't break your code in any browsers or environments but it
              will be a bit harder to figure outâ  by reading the codeâ  if the function
              was supposed to be used with or without new. And this is important because
              when the function that was intended to be used with new is used without it,
              this will point to the global object instead of a new object.

              This option prohibits the use of arguments.caller and arguments.callee. Both
              .caller and .callee make quite a few optimizations impossible so they were
noarg         deprecated in future versions of JavaScript. In fact, ECMAScript 5 forbids
              the use of arguments.callee in strict mode.

              This option warns when you have an empty block in your code. JSLint was
              originally warning for all empty blocks and we simply made it optional. There
noempty       were no studies reporting that empty blocks in JavaScript break your code in
              any way.

              This option prohibits the use of constructor functions for side-effects. Some
              people like to call constructor functions without assigning its result to any
              variable:

nonew         new MyConstructor();

              There is no advantage in this approach over simply calling MyConstructor
              since the object that the operator new creates isn't used anywhere so you
              should generally avoid constructors like this one.

              This option prohibits the use of unary increment and decrement operators.
              Some people think that ++ and -- reduces the quality of their coding styles
plusplus      and there are programming languagesâ  such as Pythonâ  that go completely
              without these operators.

              This option enforces the consistency of quotation marks used throughout your
              code. It accepts three values: true if you don't want to enforce one
quotmark      particular style but want some consistency, "single" if you want to allow
              only single quotes and "double" if you want to allow only double quotes.

              This option prohibits the use of explicitly undeclared variables. This option
              is very useful for spotting leaking and mistyped variables.

              /*jshint undef:true */

              function test() {
undef           var myVar = 'Hello, World';
                console.log(myvar); // Oops, typoed here. JSHint with undef will complain
              }

              If your variable is defined in another file, you can use /*global ... */
              directive to tell JSHint about it.

              This option warns when you define and never use your variables. It is very
              useful for general code cleanup, especially when used in addition to undef.

              /*jshint unused:true */

              function test(a, b) {
                var c, d = 2;

                return a + d;
              }

unused        test(1, 2);

              // Line 3: 'b' was defined but never used.
              // Line 4: 'c' was defined but never used.

              In addition to that, this option will warn you about unused global variables
              declared via /*global ... */ directive.

              This can be set to "vars" to only check for variables, not function
              parameters, or "strict" to check all variables and parameters. The default
              (true) behavior is to allow unused parameters that are followed by a used
              parameter.

              This option requires all functions to run in ECMAScript 5's strict mode.
              Strict mode is a way to opt in to a restricted variant of JavaScript. Strict
              mode eliminates some JavaScript pitfalls that didn't cause errors by changing
              them to produce errors. It also fixes mistakes that made it difficult for the
              JavaScript engines to perform certain optimizations.
strict
              Note: This option enables strict mode for function scope only. It prohibits
              the global scoped strict mode because it might break third-party widgets on
              your page. If you really want to use global strict mode, see the globalstrict
              option.

              This option makes it an error to leave a trailing whitespace in your code.
              Trailing whitespaces can be source of nasty bugs with multi-line strings in
              JavaScript:

trailing      // This otherwise perfectly valid string will error if
              // there is a whitespace after \
              var str = "Hello \
              World";

              This option lets you set the max number of formal parameters allowed per
              function:

              /*jshint maxparams:3 */

              function login(request, onSuccess) {
maxparams       // ...
              }

              // JSHint: Too many parameters per function (4).
              function logout(request, isManual, whereAmI, onSuccess) {
                // ...
              }

              This option lets you control how nested do you want your blocks to be:

              /*jshint maxdepth:2 */

              function main(meaning) {
                var day = true;

                if (meaning === 42) {
maxdepth          while (day) {
                        shuffle();

                    if (tired) { // JSHint: Blocks are nested too deeply (3).
                                sleep();
                    }
                  }
                }
              }

              This option lets you set the max number of statements allowed per function:

              /*jshint maxstatements:4 */

              function main() {
                var i = 0;
                var j = 0;

                // Function declarations count as one statement. Their bodies
                // don't get taken into account for the outer function.
maxstatements   function inner() {
                  var i2 = 1;
                  var j2 = 1;

                  return i2 + j2;
                }

                j = i + j;
                return j; // JSHint: Too many statements per function. (5)
              }

              This option lets you control cyclomatic complexity throughout your code.
              Cyclomatic complexity measures the number of linearly independent paths
maxcomplexity through a program's source code. Read more about cyclomatic complexity on
              Wikipedia.

maxlen        This option lets you set the maximum length of a line.


Relaxing options

             This option suppresses warnings about missing semicolons. There is
             a lot of FUD spread about semicolon spreaded by quite a few people
             in the community. The common myths are that semicolons are
             required all the time (they are not) and that they are unreliable.
             JavaScript has rules about semicolons which are followed by all
asi          browsers so it is up to you to decide whether you should or should
             not use semicolons in your code.

             For more information about semicolons in JavaScript read An Open
             Letter to JavaScript Leaders Regarding Semicolons by Isaac
             Schlueter and JavaScript Semicolon Insertion.

             This option suppresses warnings about the use of assignments in
             cases where comparisons are expected. More often than not, code
             like if (a = 10) {} is a typo. However, it can be useful in cases
boss         like this one:

             for (var i = 0, person; person = people[i]; i++) {}

             This option suppresses warnings about the debugger statements in
debug        your code.

             This option suppresses warnings about == null comparisons. Such
eqnull       comparisons are often useful when you want to check if a variable
             is null or undefined.

             This option tells JSHint that your code uses ECMAScript 6 specific
             syntax. Note that these features are not finalized yet and not all
             browsers implement them.
esnext
             More info:

               * Draft Specification for ES.next (ECMA-262 Ed. 6)

             This option suppresses warnings about the use of eval. The use of
             eval is discouraged because it can make your code vulnerable to
evil         various injection attacks and it makes it hard for JavaScript
             interpreter to do certain optimizations.

             This option suppresses warnings about the use of expressions where
             normally you would expect to see assignments or function calls.
expr         Most of the time, such code is a typo. However, it is not
             forbidden by the spec and that's why this warning is optional.

             This option suppresses warnings about declaring variables inside
             of control structures while accessing them later from the outside.
             Even though JavaScript has only two real scopesâ  global and
             functionâ  such practice leads to confusion among people new to
             the language and hard-to-debug bugs. This is why, by default,
             JSHint warns about variables that are used outside of their
             intended scope.

funcscope    function test() {
               if (true) {
                 var x = 0;
               }

               x += 1; // Default: 'x' used out of scope.
                             // No warning when funcscope:true
             }

             This option suppresses warnings about the use of global strict
             mode. Global strict mode can break third-party widgets so it is
globalstrict not recommended.

             For more info about strict mode see the strict option.

             This option suppresses warnings about the __iterator__ property.
iterator     This property is not supported by all browsers so use it
             carefully.

             This option suppresses warnings about missing semicolons, but only
             when the semicolon is omitted for the last statement in a one-line
             block:

lastsemic    var name = (function() { return 'Anton' }());

             This is a very niche use case that is useful only when you use
             automatic JavaScript code generators.

             This option suppresses most of the warnings about possibly unsafe
             line breakings in your code. It doesn't suppress warnings about
laxbreak     comma-first coding style. To suppress those you have to use
             laxcomma (see below).

             This option suppresses warnings about comma-first coding style:

             var obj = {
laxcomma         name: 'Anton'
               , handle: 'valueof'
               , role: 'SW Engineer'
             };

             This option suppresses warnings about functions inside of loops.
             Defining functions inside of loops can lead to bugs such as this
             one:

             var nums = [];

             for (var i = 0; i < 10; i++) {
               nums[i] = function (j) {
                 return i + j;
               };
             }

loopfunc     nums[0](2); // Prints 12 instead of 2

             To fix the code above you need to copy the value of i:

             var nums = [];

             for (var i = 0; i < 10; i++) {
               (function (i) {
                 nums[i] = function (j) {
                     return i + j;
                 };
               }(i));
             }

             This options tells JSHint that your code uses Mozilla JavaScript
             extensions. Unless you develop specifically for the Firefox web
             browser you don't need this option.
moz
             More info:

               * New in JavaScript 1.7

             This option suppresses warnings about multi-line strings.
             Multi-line strings can be dangerous in JavaScript because all hell
             breaks loose if you accidentally put a whitespace in between the
             escape character (\) and a new line.

             Note that even though this option allows correct multi-line
             strings, it still warns about multi-line strings without escape
             characters or with anything in between the escape character and a
             whitespace.

multistr     /*jshint multistr:true */

             var text = "Hello\
             World"; // All good.

             text = "Hello
             World"; // Warning, no escape character.

             text = "Hello\
             World"; // Warning, there is a space after \

proto        This option suppresses warnings about the __proto__ property.

             This option suppresses warnings about the use of script-targeted
scripturl    URLsâ  such as javascript:....

             This option suppresses warnings about mixed tabs and spaces when
smarttabs    the latter are used for alignmnent only. The technique is called
             SmartTabs.

             This option suppresses warnings about variable shadowing i.e.
shadow       declaring a variable that had been already declared somewhere in
             the outer scope.

             This option suppresses warnings about using [] notation when it
sub          can be expressed in dot notation: person['name'] vs. person.name.

             This option suppresses warnings about "weird" constructions like
             new function () { ... } and new Object;. Such constructions are
             sometimes used to produce singletons in JavaScript:

             var singleton = new function() {
supernew       var privateVar;

               this.publicMethod  = function () {}
               this.publicMethod2 = function () {}
             };

             This option suppresses warnings about possible strict violations
             when the code is running in strict mode and you use this in a
             non-constructor function. You should use this optionâ  in a
             function scope onlyâ  when you are positive that your use of this
             is valid in the strict mode (for example, if you call your
validthis    function using Function.call).

             Note: This option can be used only inside of a function scope.
             JSHint will fail with an error if you will try to set this option
             globally.


Environments

These options pre-define global variables that are exposed by popular
JavaScript libraries and runtime environmentsâ  such as browser or Node.
Essentially they are shortcuts for explicit declarations like /*global $:false,
jQuery:false */.

            This option defines globals exposed by modern browsers: all the way
            from good old document and navigator to the HTML5 FileReader and
            other new developments in the browser world.
browser
            Note: This option doesn't expose variables like alert or console.
            See option devel for more information.

            This option defines globals exposed by CouchDB. CouchDB is a
couch       document-oriented database that can be queried and indexed in a
            MapReduce fashion using JavaScript.

            This option defines globals that are usually used for logging
            poor-man's debugging: console, alert, etc. It is usually a good
devel       idea to not ship them in production because, for example,
            console.log breaks in legacy versions of Internet Explorer.

dojo        This option defines globals exposed by the Dojo Toolkit.

            This option defines globals exposed by the jQuery JavaScript
jquery      library.

            This option defines globals exposed by the MooTools JavaScript
mootools    framework.

            This option defines globals available when your code is running
            inside of the Node runtime environment. Node.js is a server-side
node        JavaScript environment that uses an asynchronous event-driven
            model.

            This option defines non-standard but widely adopted globals such as
nonstandard escape and unescape.

            This option defines globals exposed by the Prototype JavaScript
prototypejs framework.

            This option defines globals available when your code is running
rhino       inside of the Rhino runtime environment. Rhino is an open-source
            implementation of JavaScript written entirely in Java.

            This option defines globals available when your code is running
worker      inside of a Web Worker. Web Workers provide a simple means for web
            content to run scripts in background threads.

            This option defines globals available when your code is running as
wsh         a script for the Windows Script Host.

yui         This option defines globals exposed by the YUI JavaScript
            framework.

Legacy

These options are legacy from JSLint. Aside from bug fixes they will not be
improved in any way and might be removed at any point.

         This option disallows the use of dangling _ in variables. We don't
nomen    know why would you need it.

         This option allows only one var statement per function. Some people
         think that having a single var in a function, at the top of the
         function, helps readability. Example (taken from JSLint/JSHint source
         code):

         x.nud = function () {
           var b, f, i, j, p, seen = {}, t;

           b = token.line !== nexttoken.line;
onevar     if (b) {
             indent += option.indent;
             if (nexttoken.from === indent + option.indent) {
                           indent += option.indent;
                   }
           }

           // [...]
         };

passfail This option makes JSHint stop on the first error or warning.

         This option make JSHint check your source code against Douglas
white    Crockford's JavaScript coding style. Unfortunately, his â  The Good
         Partsâ   book aside, the actual rules are not very well documented.

Still confused?

If you have any further questions about JSHint, feel free to send them to our
mailing list.

JSHint, by JSHint Community. Follow us on Twitter or GitHub.

Maintained by Anton Kovalyov. This website was made by Anton and Pierre Bertet.

