|
| 1 | +<!--- |
| 2 | +{ |
| 3 | + "titles": [ |
| 4 | + "latedef" |
| 5 | + ], |
| 6 | + "slugs": [ |
| 7 | + "option-jshint-latedef" |
| 8 | + ], |
| 9 | + "linters": [ |
| 10 | + "jshint" |
| 11 | + ], |
| 12 | + "author": "jallardice", |
| 13 | + "subject": "option" |
| 14 | +} |
| 15 | +--> |
| 16 | + |
| 17 | +### What does this option do? |
| 18 | + |
| 19 | +The JSHint `latedef` option is used to ensure variables and functions are |
| 20 | +declared before they are used. That is to say, the declarations appear |
| 21 | +physically in the source code above references to those declared variables or |
| 22 | +functions. Because declarations in JavaScript are hoisted to the top of the |
| 23 | +scope in which they occur it is perfectly safe to reference them earlier. |
| 24 | + |
| 25 | +In the following example the `doStuff` function declaration is hoisted to the |
| 26 | +top of the global scope so it is accessible throughout the program regardless of |
| 27 | +its position in the source: |
| 28 | + |
| 29 | +<!--- |
| 30 | +{ |
| 31 | + "linter": "jshint" |
| 32 | +} |
| 33 | +--> |
| 34 | +```javascript |
| 35 | +/*jshint latedef: true */ |
| 36 | +doStuff(); |
| 37 | +function doStuff() {} |
| 38 | +``` |
| 39 | + |
| 40 | +### When should I use this option? |
| 41 | + |
| 42 | +The use of the `latedef` JSHint option will cause a "['{a}' was used before it |
| 43 | +was defined][latedef]" error any time it encounters a reference to an identifier |
| 44 | +that has not yet been declared. By declaring variables and functions before you |
| 45 | +need to refer to them you can make your code easier to read through, since most |
| 46 | +people will read it from top to bottom. If a function is declared at the bottom |
| 47 | +of a file but used throughout the reader will have to scroll around to find the |
| 48 | +definition rather than immediately seeing it at the top. |
| 49 | + |
| 50 | +<!--- |
| 51 | +{ |
| 52 | + "linter": "jshint" |
| 53 | +} |
| 54 | +--> |
| 55 | +```javascript |
| 56 | +/*jshint immed: true */ |
| 57 | +function doStuff() {} |
| 58 | +doStuff(); |
| 59 | +``` |
| 60 | + |
| 61 | +Note that this is an *enforcing* option which means JSHint does not apply it by |
| 62 | +default. If you do not explicitly set this option to `true` JSHint will allow |
| 63 | +references to appear before declarations. |
| 64 | + |
| 65 | +#### Recommendation |
| 66 | + |
| 67 | +Set this option to `true` (ensures declarations appear before references). |
| 68 | + |
| 69 | +[latedef]: /a-was-used-before-it-was-defined |
0 commit comments