Try it.
See the options.
Enjoy The Good Parts.
Donate.
The JavaScript Code Quality Tool

Warning: JSLint will hurt your feelings.

What is JSLint?

JSLint is a JavaScript program that looks for problems in JavaScript programs. It is a code quality tool.

When C was a young programming language, there were several common programming errors that were not caught by the primitive compilers, so an accessory program called lint was developed that would scan a source file, looking for problems.

As the language matured, the definition of the language was strengthened to eliminate some insecurities, and compilers got better at issuing warnings. lint is no longer needed.

JavaScript is a young-for-its-age language. It was originally intended to do small tasks in webpages, tasks for which Java was too heavy and clumsy. But JavaScript is a surprisingly capable language, and it is now being used in larger projects. Many of the features that were intended to make the language easy to use are troublesome when projects become complicated. A lint for JavaScript is needed: JSLint, a JavaScript syntax checker and validator.

JSLint takes a JavaScript source and scans it. If it finds a problem, it returns a message describing the problem and an approximate location within the source. The problem is not necessarily a syntax error, although it often is. JSLint looks at some style conventions as well as structural problems. It does not prove that your program is correct. It just provides another set of eyes to help spot problems.

JSLint defines a professional subset of JavaScript, a stricter language than that defined by Third Edition of the ECMAScript Programming Language Standard. The subset is related to recommendations found in Code Conventions for the JavaScript Programming Language.

JavaScript is a sloppy language, but inside it there is an elegant, better language. JSLint helps you to program in that better language and to avoid most of the slop. JSLint will reject programs that browsers will accept because JSLint is concerned with the quality of your code and browsers are not. You should accept all of JSLint's advice.

JSLint can operate on JavaScript source, HTML source, CSS source, or JSON text.

Global Variables

JavaScript's biggest problem is its dependence on global variables, particularly implied global variables. If a variable is not explicitly declared (usually with the var statement), then JavaScript assumes that the variable was global. This can mask misspelled names and other problems.

JSLint expects that all variables and functions are declared before they are used or invoked. This allows it to detect implied global variables. It is also good practice because it makes programs easier to read.

Sometimes a file is dependent on global variables and functions that are defined elsewhere. You can identify these to JSLint with a var statement that lists the global functions and objects that your program depends on.

A global declaration can look like this:

var getElementByAttribute, breakCycles, hanoi;

The declaration should appear near the top of the file. It must appear before the use of the variables it declares.

It is necessary to use a var statement to declare a variable before that variable is assigned to.

JSLint also recognizes a /*global*/ directive that can indicate to JSLint that variables used in this file were defined in other files. The directive can contain a comma separated list of names. Each name can optionally be followed by a colon and either true or false, true indicating that the variable may be assigned to by this file, and false indicating that assignment is not allowed (which is the default). The directive respects function scope.

Some globals can be predefined for you. Select the Assume a browser (browser) option to predefine the standard global properties that are supplied by web browsers, such as document and addEventListener. It has the same effect as this directive:

/*global clearInterval: false, clearTimeout: false, document: false, event: false, frames: false, history: false, Image: false, location: false, name: false, navigator: false, Option: false, parent: false, screen: false, setInterval: false, setTimeout: false, window: false, XMLHttpRequest: false */

Select the Assume console, alert, ... (devel) option to predefine globals that are useful in development but that should be avoided in production, such as console and alert. It has the same effect as this directive:

/*global alert: false, confirm: false, console: false, Debug: false, opera: false, prompt: false, WSH: false */

Select the Assume Node.js (node) option to predefine globals that are used in the Node.js environment. It has the same effect as this directive:

/*global Buffer: false, clearInterval: false, clearTimeout: false, console: false, exports: false, global: false, module: false, process: false, querystring: false, require: false, setInterval: false, setTimeout: false, __filename: false, __dirname: false */

Select the Assume Rhino (rhino) option to predefine the global properties provided by the Rhino environment. It has the same effect as this directive:

/*global defineClass: false, deserialize: false, gc: false, help: false, load: false, loadClass: false, print: false, quit: false, readFile: false, readUrl: false, runCommand: false, seal: false, serialize: false, spawn: false, sync: false, toint32: false, version: false */

Select the Assume Windows (windows) option to predefine the global properties provided by Microsoft Windows. It has the same effect as this directive:

/*global ActiveXObject: false, CScript: false, Debug: false, Enumerator: false, System: false, VBArray: false, WScript: false, WSH: false */

Semicolon

JavaScript uses a C-like syntax which requires the use of semicolons to delimit certain statements. JavaScript attempts to make those semicolons optional with a semicolon insertion mechanism. This is dangerous because it can mask errors.

Like C, JavaScript has ++ and -- and ( operators which can be prefixes or suffixes. The disambiguation is done by the semicolon.

In JavaScript, a linefeed can be whitespace or it can act as a semicolon. This replaces one ambiguity with another.

JSLint expects that every statement be followed by ; except for for, function, if, switch, try, and while. JSLint does not expect to see unnecessary semicolons or the empty statement.

Comma

The comma operator can lead to excessively tricky expressions. It can also mask some programming errors.

JSLint expects to see the comma used as a separator, but not as an operator (except in the initialization and incrementation parts of the for statement). It does not expect to see elided elements in array literals. Extra commas should not be used. A comma should not appear after the last element of an array literal or object literal because it can be misinterpreted by some browsers.

Scope

In many languages, a block introduces a scope. Variables introduced in a block are not visible outside of the block.

In JavaScript, blocks do not introduce a scope. There is only function-scope. A variable introduced anywhere in a function is visible everywhere in the function. JavaScript's blocks confuse experienced programmers and lead to errors because the familiar syntax makes a false promise.

JSLint expects blocks with function, if, switch, while, for, do, and try statements and nowhere else.

In languages with block scope, it is usually recommended that variables be declared at the site of first use. But because JavaScript does not have block scope, it is wiser to declare all of a function's variables at the top of the function. It is recommended that a single var statement be used per function. This can be declined with the vars option.

Required Blocks

JSLint expects that if, while, do and for statements will be made with blocks {that is, with statements enclosed in braces}.

JavaScript allows an if to be written like this:

if (condition) statement;

That form is known to contribute to mistakes in projects where many programmers are working on the same code. That is why JSLint expects the use of a block:

if (condition) { statements; }

Experience shows that this form is more resilient.

Expression Statements

An expression statement is expected to be an assignment or a function/method call or delete. All other expression statements are considered to be errors.

for in

The for in statement allows for looping through the names of all of the properties of an object. Unfortunately, it also loops through all of the properties that were inherited through the prototype chain. This has the bad side effect of serving up method functions when the interest is in data properties. If a program is written without awareness of this situation, then it can fail.

The body of every for in statement should be wrapped in an if statement that does filtering. It can select for a particular type or range of values, or it can exclude functions, or it can exclude properties from the prototype. For example,

for (name in object) { if (object.hasOwnProperty(name)) { .... } }

switch

A common error in switch statements is to forget to place a break statement after each case, resulting in unintended fall-through. JSLint expects that the statement before the next case or default is one of these: break, return, or throw.

var

JavaScript allows var definitions to occur anywhere within a function. JSLint is more strict.

JSLint expects that a var will be declared only once, and that it will be declared before it is used.

JSLint expects that a function will be declared before it is used.

JSLint expects that parameters will not also be declared as vars.

JSLint does not expect the arguments array to be declared as a var.

JSLint does not expect that a var will be defined in a block. This is because JavaScript blocks do not have block scope. This can have unexpected consequences. Define all variables at the top of the function.

with

The with statement was intended to provide a shorthand in accessing properties in deeply nested objects. Unfortunately, it behaves very badly when setting new properties. Never use the with statement. Use a var instead.

JSLint does not expect to see a with statement.

=

JSLint does not expect to see an assignment statement in the condition part of an if or for or while or do statement. This is because it is more likely that

if (a = b) { ... }

was intended to be

if (a == b) { ... }

It is difficult to write correct programs while using idioms that are hard to distinguish from obvious errors.

== and !=

The == and != operators do type coercion before comparing. This is bad because it causes ' \t\r\n' == 0 to be true. This can mask type errors. JSLint cannot reliably determine if == is being used correctly, so it is best to not use == and != at all and to always use the more reliable === and !== operators instead.

If you only care that a value is truthy or falsy, then use the short form. Instead of

(foo != 0)

just say

(foo)

and instead of

(foo == 0)

say

(!foo)

There is an eqeq option that allows the use of == and !=.

Labels

JavaScript allows any statement to have a label, and labels have a separate name space. JSLint is more strict.

JSLint expects labels only on statements that interact with break: switch, while, do, and for. JSLint expects that labels will be distinct from vars and parameters.

Unreachable Code

JSLint expects that a return, break, continue, or throw statement will be followed by a } or case or default.

Confusing Pluses and Minuses

JSLint expects that + will not be followed by + or ++, and that - will not be followed by - or --. A misplaced space can turn + + into ++, an error that is difficult to see. Use parens to avoid confusion..

++ and --

The ++ (increment) and -- (decrement) operators have been known to contribute to bad code by encouraging excessive trickiness. They are second only to faulty architecture in enabling to viruses and other security menaces. Also, preincrement/postincrement confusion can produce off-by-one errors that are extremely difficult to diagnose. There is a plusplus option that allows the use of these operators.

Bitwise Operators

JavaScript does not have an integer type, but it does have bitwise operators. The bitwise operators convert their operands from floating point to integers and back, so they are not as efficient as in C or other languages. They are rarely useful in browser applications. The similarity to the logical operators can mask some programming errors. The bitwise option allows the use of these operators: << >> >>> ~ & |.

eval is evil

The eval function (and its relatives, Function, setTimeout, and setInterval) provide access to the JavaScript compiler. This is sometimes necessary, but in most cases it indicates the presence of extremely bad coding. The eval function is the most misused feature of JavaScript.

void

In most C-like languages, void is a type. In JavaScript, void is a prefix operator that always returns undefined. JSLint does not expect to see void because it is confusing and not very useful.

Regular Expressions

Regular expressions are written in a terse and cryptic notation. JSLint looks for problems that may cause portability problems. It also attempts to resolve visual ambiguities by recommending explicit escapement.

JavaScript's syntax for regular expression literals overloads the / character. To avoid ambiguity, JSLint expects that the character preceding a regular expression literal is a ( or = or : or , character.

Constructors and new

Constructors are functions that are designed to be used with the new prefix. The new prefix creates a new object based on the function's prototype, and binds that object to the function's implied this parameter. If you neglect to use the new prefix, no new object will be made and this will be bound to the global object. This is a serious mistake.

JSLint enforces the convention that constructor functions be given names with initial uppercase. JSLint does not expect to see a function invocation with an initial uppercase name unless it has the new prefix. JSLint does not expect to see the new prefix used with functions whose names do not start with initial uppercase. This can be disabled with the newcap option.

JSLint does not expect to see the wrapper forms new Number, new String, new Boolean.

JSLint does not expect to see new Object. Use {} instead.

JSLint does not expect to see new Array. Use [] instead.

Properties

Since JavaScript is a loosely-typed, dynamic-object language, it is not possible to determine at compile time if property names are spelled correctly. JSLint provides some assistance with this.

At the bottom of its report, JSLint displays a /*properties*/ directive. It contains all of the names and string literals that were used with dot notation, subscript notation, and object literals to name the properties of objects. You can look through the list for misspellings. This is to make misspellings easier to spot.

You can copy the /*properties*/ directive into the top of your script file. JSLint will check the spelling of all property names against the list. That way, you can have JSLint look for misspellings for you.

For example,

/*properties charAt, slice */

Unsafe Characters

There are characters that are handled inconsistently in browsers, and so must be escaped when placed in strings.

\u0000-\u001f \u007f-\u009f \u00ad \u0600-\u0604 \u070f \u17b4 \u17b5 \u200c-\u200f \u2028-\u202f \u2060-\u206f \ufeff \ufff0-\uffff

Not Looked For

JSLint does not do flow analysis to determine that variables are assigned values before used. This is because variables are given a value (undefined) that is a reasonable default for many applications.

JSLint does not do any kind of global analysis. It does not attempt to determine that functions used with new are really constructors (except by enforcing capitalization conventions), or that property names are spelled correctly (except for matching against the /*properties*/ directive).

HTML

JSLint is able to handle HTML text. It can inspect the JavaScript content contained within <script>...</script> tags. It also inspects the HTML content, looking for problems that are known to interfere with JavaScript:

JSLint is less anal than the sycophantic conformity demanded by XHTML, but more strict than the popular browsers.

JSLint also checks for the occurrence of '</' in string literals. You should always write '<\/' instead. The extra backslash is ignored by the JavaScript compiler but not by the HTML parser. Tricks like this should not be necessary, and yet they are.

There is a fragment option that can inspect a well formed HTML fragment. If the adsafe option is also used, then the fragment must be a <div> that conforms to the ADsafe widget rules.

CSS

JSLint can inspect CSS files. It expects the first line of a CSS file to be

@charset "UTF-8";

This feature is experimental. Please report any problems or limitations. There is a css option that will tolerate some of the non-standard-but-customary workarounds.

Options

JSLint provides several options that control its operation and its sensitivity. In the web edition, the options are selected with several checkboxes and two fields.

It also provides assistance in constructing /*jslint*/ and /*properties*/ directives.

When JSLINT is called as a function, it accepts an option object parameter that allows you to determine the subset of JavaScript that is acceptable to you. The web page version of JSLint at jslint.html does this for you.

Options can also be specified within a script with a /*jslint*/ directive:

/*jslint nomen: true, debug: true, evil: false, vars: true */

An option directive starts with /*jslint. Notice that there is no space before the j. The specification contains a sequence of name value pairs, where the names are JSLint options, and the values are true or false. The indent option can take a number. A /*jslint*/ directive takes precedence over the option object. The directive respects function scope.

Description option Meaning
ADsafe adsafe true if ADsafe rules should be enforced. See http://www.ADsafe.org/. adsafe is used with the option object, but not with the /*jslint*/ directive.
Tolerate bitwise operators bitwise true if bitwise operators should be allowed. (more)
Assume a browser browser true if the standard browser globals should be predefined. (more)
Tolerate continue continue true if the continue statement should be allowed.
Tolerate CSS workarounds css true if CSS workarounds should be tolerated. (more)
Tolerate debugger statements debug true if debugger statements should be allowed. Set this option to false before going into production.
Assume console, alert, ... devel true if browser globals that are useful in development should be predefined. (more)
Tolerate == and != eqeq true if the == and != operators should be tolerated. (more)
Tolerate ES5 syntax es5 true if ES5 syntax should be allowed. It is likely that programs using this option will produce syntax errors on ES3 systems.
Tolerate eval evil true if eval should be allowed. (more)
Tolerate unfiltered for in forin true if unfiltered for in statements should be allowed. (more)
Tolerate HTML fragments fragment true if HTML fragments should be allowed. (more)
Strict white space indentation indent The number of spaces used for indentation (default is 4).
Maximum number of errors maxerr The maximum number of warnings reported. (default is 50)
Maximum line length maxlen The maximum number of characters in a line.
Tolerate uncapitalized constructors newcap true if Initial Caps with constructor functions is optional. (more)
Assume Node.js node true if Node.js globals should be predefined. (more)
Tolerate dangling _ in identifiers nomen true if names should not be checked for initial or trailing underbars.
Tolerate HTML event handlers on true if HTML event handlers should be allowed. (more)
Stop on first error passfail true if the scan should stop on first error.
Tolerate ++ and -- plusplus true if ++ and -- should be allowed. (more)
Predefined ( , separated) predef An array of strings, the names of predefined global variables, or an object whose keys are global variable names, and whose values are booleans that determine if each variable is assignable (also see global). predef is used with the option object, but not with the /*jslint*/ directive. You can also use the var statement to declare global variables in a script file.
Tolerate . and [^...]. in /RegExp/ regexp true if . and [^...] should be allowed in RegExp literals. They match more material than might be expected, allowing attackers to confuse applications. These forms should not be used when validating in secure applications.
Assume Rhino rhino true if the Rhino environment globals should be predefined. (more)
Safe Subset safe true if the safe subset rules are enforced. These rules are used by ADsafe. It enforces the safe subset rules but not the widget structure rules. safe is used with the option object, but not with the /*jslint*/ directive.
Tolerate missing 'use strict' pragma sloppy true if the ES5 'use strict'; pragma is not required. Do not use this pragma unless you know what you are doing.
Tolerate stupidity
stupid true if blocking ('...Sync') methods can be used.
Tolerate inefficient subscripting
sub true if subscript notation may be used for expressions better expressed in dot notation.
Tolerate TODO comments
todo true if comments starting with TODO should be allowed.
Tolerate misordered definitions undef true if variables and functions need not be declared before used. This is not available in strict mode.
Tolerate unused parameters unparam true if warnings should not be given for unused parameters.
Tolerate many var statements per function vars true if multiple var statement per function should be allowed. (more)
Tolerate messy white space white true if strict whitespace rules should be ignored.
Assume Windows windows true if the Windows globals should be predefined. (more)

Report

If JSLint is able to complete its scan, it generates a function report. It lists for each function:

The report will also include a list of all of the property names that were used. There is a list of JSLint messages.

Feedback

Please let me know if JSLint is useful for you. Is it too strict? Is there a check or a report that could help you to improve the quality of your programs? douglas@crockford.com. But please don't ask me to dumb JSLint down or to make it more forgiving of bad practices. You would only be disappointed.

I intend to continue to adapt JSLint based on your comments. Keep watching for improvements. Updates are announced at http://tech.groups.yahoo.com/group/jslint_com/.

Try it

Try it. Paste your script into the window and click the button. The analysis is done by a script running on your machine. Your script is not sent over the network. You can set the options used.

JSLint is written entirely in JavaScript, so it can run anywhere that JavaScript can run. See for example http://tech.groups.yahoo.com/group/jslint_com/database?method=reportRows&tbl=1.

Implementation

JSLint uses a Pratt Parser (Top Down Operator Precedence). It is written in JavaScript. The full source code is available: https://github.com/douglascrockford/JSLint.