jscorrect option
Introduction
Pretty Diff, more specifically the jspretty library, features an option called jscorrect. The option allows Pretty Diff to alter JavaScript code in favor of some common best practices. The intentions of this feature are to make code easier for humans to read and eliminate many errors returned by common validation tools.
Read the API documentation.
Features
- brace insertion — Curly braces are optional for all blocks in JavaScript except functions and object literals. When curly braces are omitted a block is presumed to apply for only the single most immediately following statement, which can be identified by placement of a semicolon (after automatic semicolon insertion). These rules make code confusing to read and challenging to understand, particularly when these blocks are nested. The jscorrect option will insert the missing curly braces into the code.
- automatic semicolon insertion — Automatic semicolon insertion (ASI) is a controversial feature provided to JavaScript to help prevent application failure if a code author forgets a semicolon. Semicolons are required at the end of code statements. ASI is applied when a line break occurs in code (provided a set of rules) and after curly braces if the curly braces represent a block that is the tail end of a statement. ASI is complex to apply for many various edge cases and so results in potential errors and faulty assumptions when writing code. A general best practice is to never forget semicolons. The jscorrect option will insert semicolons that are otherwise added anyways during code interpretation.
- ++ and -- operator conversion — The ++ and -- operators mean to increment and decrement a variable by 1, respectively. These operators mean different things if they prefix or suffix the variable they modify. This is complicated on its own, but it is even more complicated when this operator is used in an expression. For the sake of sanity and universal clarity it is suggested to use += 1 or -= 1 instead. In the cases where the use of ++ or -- is extremely predictable Pretty Diff automatically convert it to the better alternatives.
- new Array() and new Object() — It is possible to declare an array or object use this funny object oriented approach. This is completely unnecessary and requires extra work of the interpreter. The preferred approach is to simply assign a reference to an empty array [] or empty object {}. This conversion is automatic thanks to Pretty Diff.