Javascript Style Checker


Despite many years of experience, people still type variable names incorrectly, make syntax errors and forget to handle errors properly and forget about the best practices in hurry. But its important to write the quality code. A good linting tool, or a linter, will help to check the code errors and the standard style before someone waste their time—or worse, client’s time.

First of all, I will be describing some standard javascript rules and then the lint tools available to check for javascript standard and how the tools can be integrated with IntelliJ IDEA.

Some Standard JavaScript rules.

  • Use 2 spaces for indentation

  function hello (name) {
    console.log('hi', name)
 }
  • Use single quotes for strings except to avoid escaping.

  console.log('hello there')
  $("
<div class = 'box' ")
  • No unused variables

  function myFunction () {
    var result = something()                    // avoid
  }
    • Add a space after keywords.

  if (condition) { ... }                       // OK
  if(condition) { ... }                        // Avoid
    • Add a space before a function declaration’s parentheses.

  function name (arg) { ... }                 // OK
  function name(arg) { ... }                  // Avoid
    • Always use=== instead of ==.

Exception: obj == null is allowed to check for null || undefined.
  if (name === 'John')                          //OK
  if (name == 'John')                           //Avoid
  if (name !== 'John')                          // OK
  if (name != 'John')                           //Avoid
    • Infix operators must be spaced

  var message = 'hello, ' + name + '!'         // OK
  var message = 'hello, ' +name+'!'            // Avoid
    • Commas should have a space after them

  var list = [1, 2, 3, 4]                       // OK
  var list = [1,2,3,4]                          // Avoid
    • Always handle the err function parameter

OK
  run(function (err) {
    if (err) throw err
    window.alert('done')
  })

Avoid
  run(function (err) {
    window.alert('done')
  })

Lint Tools

Despite many years of experience, one can still type variable names incorrectly, make syntax errors and forget to handle errors properly. A good linting tool, or a linter, will tell about this before wastage of time—or worse, client’s time. A good linting tool can also help make sure a project adheres to a coding standard. A linting tool helps to avoid silly mistakes when writing JavaScript.

Different Lint Tools

Different tools available are:

  • JSLint

  • JSHint

  • JSCS

  • ESLint

JSLint

Pros

  • Comes configured and ready to go (if you agree with the rules it enforces)

Cons

  1. JSLint doesn’t have a configuration file, which can be problematic if you need to change the settings

  2. Limited number of configuration options, many rules cannot be disabled

  3. You can’t add custom rules

  4. Undocumented features

  5. Difficult to know which rule is causing which error

JSHint

JSHint was created as a more configurable version of JSLint (of which it is a fork). You can configure every rule, and put them into a configuration file, which makes JSHint easy to use in bigger projects.

Pros

  1. Most settings can be configured

  2. Supports a configuration file, making it easier to use in larger projects

  3. Has support for many libraries out of the box, like jQuery, QUnit, NodeJS, Mocha, etc.

Cons

  1. Difficult to know which rule is causing an error.

  2. Has two types of option: enforcing and relaxing (which can be used to make JSHint stricter, or to suppress its warnings). This can make configuration slightly confusing.

  3. No custom rule support

JSCS

JSCS is different from the others in that it doesn’t do anything unless you give it a configuration file or tell it to use a preset

Pros

  1. Ready-made configuration files can make it easy to set up if you follow one of the available coding styles

  2. Has a flag to include rule names in reports, so it’s easy to figure out which rule is causing which error

  3. Can be extended with custom plugins

    Cons

  1. Only detects coding style violations. JSCS doesn’t detect potential bugs such as unused variables, or accidental globals, etc.

  2. Slowest of the four, but this is not a problem in typical use

ESLint

Pros

  1. Flexible: any rule can be toggled, and many rules have extra settings that can be tweaked

  2. Very extensible and has many plugins available

  3. Easy to understand output

  4. Includes many rules not available in other linters, making ESLint more useful for detecting problem

Cons

  1. Some configuration required.

  2. Slow, but not a hindrance.

After considering the pros and cons, I would suggest to use ESLint. Even the JSCS and ESLint teams have agreed upon making ESLint together instead of competing with each other.

How to use?

Three requirements :

1) It requires Node.js

2) To include ESLint as part of your project’s build system. (I.e having esLint installed)

3) You should then setup a configuration file (having .eslintrc.json file).

To run ESLint using intellij:

  • File | Settings | Languages and Frameworks | JavaScript | Code Quality Tools | ESLint
  • Support displaying eslint warnings as intellij inspections

    blog2

 

 

 

 

 

 

 

 

 

Configuring Rules:

(Rules can be added in .eslintrc.json):

{
“rules”: {
“semi”: [“error”, “always”],
“quotes”: [“error”, “double”]
}
}

The names “semi” and “quotes” are the names of rules in ESLint. The first value is the error level of the rule and can be one of these values:

  • “off” or 0 turn the rule off

  • “warn” or 1 – turn the rule on as a warning (doesn’t affect exit code)

  • “error” or 2 – turn the rule on as an error (exit code will be 1)

Sample .eslintrc.json file :

{
    "extends": "google",
    "installedESLint": true,
    "rules": {
    "accessor-pairs": 2,
    "arrow-spacing": [2, { "before": true, "after": true }],
    "block-spacing": [2, "always"],
    "brace-style": [2, "1tbs", { "allowSingleLine": true }],
    "camelcase": [2, { "properties": "never" }],
    "comma-dangle": [2, "never"],
    "comma-spacing": [2, { "before": false, "after": true }],
    "comma-style": [2, "last"],
    "constructor-super": 2,
    "curly": [2, "multi-line"],
    "dot-location": [2, "property"],
    "eol-last": 2,
    "eqeqeq": [2, "allow-null"],
    "handle-callback-err": [2, "^(err|error)$" ],
    "indent": [2, 2, { "SwitchCase": 1 }],
    "key-spacing": [2, { "beforeColon": false, "afterColon": true }],
    "keyword-spacing": [2, { "before": true, "after": true }],
    "new-cap": [2, { "newIsCap": true, "capIsNew": false }],
    "new-parens": 2,
    "no-array-constructor": 2,
    "no-caller": 2,
    "no-class-assign": 2,
    "no-cond-assign": 2,
    "no-const-assign": 2,
    "no-constant-condition": [2, { "checkLoops": false }],
    "no-control-regex": 2,
    "no-debugger": 2,
    "no-delete-var": 2,
    "no-dupe-args": 2,
    "no-dupe-class-members": 2,
    "no-dupe-keys": 2,
    "no-duplicate-case": 2,
    "no-duplicate-imports": 2,
    "no-empty-character-class": 2,
    "no-empty-pattern": 2,
    "no-eval": 2,
    "no-ex-assign": 2,
    "no-extend-native": 2,
    "no-extra-bind": 2,
    "no-extra-boolean-cast": 2,
    "no-extra-parens": [2, "functions"],
    "no-fallthrough": 2,
    "no-floating-decimal": 2,
    "no-func-assign": 2,
    "no-implied-eval": 2,
    "no-inner-declarations": [2, "functions"],
    "no-invalid-regexp": 2,
    "no-irregular-whitespace": 2,
    "no-iterator": 2,
    "no-label-var": 2,
    "no-labels": [2, { "allowLoop": false, "allowSwitch": false }],
    "no-lone-blocks": 2,
    "no-mixed-spaces-and-tabs": 2,
    "no-multi-spaces": 2,
    "no-multi-str": 2,
    "no-multiple-empty-lines": [2, { "max": 1 }],
    "no-native-reassign": 2,
    "no-negated-in-lhs": 2,
    "no-new": 2,
    "no-new-func": 2,
    "no-new-object": 2,
    "no-new-require": 2,
    "no-new-symbol": 2,
    "no-new-wrappers": 2,
    "no-obj-calls": 2,
    "no-octal": 2,
    "no-octal-escape": 2,
    "no-path-concat": 2,
    "no-proto": 2,
    "no-redeclare": 2,
    "no-regex-spaces": 2,
    "no-return-assign": [2, "except-parens"],
    "no-self-assign": 2,
    "no-self-compare": 2,
    "no-sequences": 2,
    "no-shadow-restricted-names": 2,
    "no-spaced-func": 2,
    "no-sparse-arrays": 2,
    "no-this-before-super": 2,
    "no-throw-literal": 2,
    "no-trailing-spaces": 2,
    "no-undef": 2,
    "no-undef-init": 2,
    "no-unexpected-multiline": 2,
    "no-unmodified-loop-condition": 2,
    "no-unneeded-ternary": [2, { "defaultAssignment": false }],
    "no-unreachable": 2,
    "no-unsafe-finally": 2,
    "no-unused-vars": [2, { "vars": "all", "args": "none" }],
    "no-useless-call": 2,
    "no-useless-computed-key": 2,
    "no-useless-constructor": 2,
    "no-useless-escape": 2,
    "no-useless-rename": 2,
    "no-whitespace-before-property": 2,
    "no-with": 2,
    "object-property-newline": [2, { "allowMultiplePropertiesPerLine": true }],
    "one-var": [2, { "initialized": "never" }],
    "operator-linebreak": [2, "after", { "overrides": { "?": "before", ":": "before" } }],
    "padded-blocks": [2, "never"],
    "quotes": [2, "single", { "avoidEscape": true, "allowTemplateLiterals": true }],
    "rest-spread-spacing": [2, "never"],
    "semi": [2, "never"],
    "semi-spacing": [2, { "before": false, "after": true }],
    "space-before-blocks": [2, "always"],
    "space-before-function-paren": [2, "always"],
    "space-in-parens": [2, "never"],
    "space-infix-ops": 2,
    "space-unary-ops": [2, { "words": true, "nonwords": false }],
    "spaced-comment": [2, "always", { "line": { "markers": ["*package", "!", ","] }, "block": { "balanced": true, "markers": ["*package", "!", ","], "exceptions": ["*"] } }],
    "template-curly-spacing": [2, "never"],
    "unicode-bom": [2, "never"],
    "use-isnan": 2,
    "valid-typeof": 2,
    "wrap-iife": [2, "any"],
    "yield-star-spacing": [2, "both"],
    "yoda": [2, "never"],

    "standard/object-curly-even-spacing": [2, "either"],
    "standard/array-bracket-even-spacing": [2, "either"],
    "standard/computed-property-even-spacing": [2, "even"],

    "promise/param-names": 2
  }
}

References:

1) https://github.com/eslint/eslint

2) https://www.sitepoint.com/comparison-javascript-linting-tools/


KNOLDUS-advt-sticker

This entry was posted in Scala. Bookmark the permalink.

4 Responses to Javascript Style Checker

  1. Thank you! Very helpful for newbies trying to form good habits.

  2. Pingback: Share: Javascript Style Checker | Transformation Through Web Development

  3. Pingback: JavaScript Style Checker – My Personal Diary

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s