Jslint is suddenly reporting: Use the function form of "use strict"
If you're getting a warning from JSLint about 'use strict', it can be resolved by wrapping your code in an Immediate Invoking Function Expression (IIFE). Naughty warnings go away through this containment:
This injects strict mode into your function's safe house which keeps the global scope out of its strict business.
Understanding the function form of "use strict"
Strict mode in JavaScript isn't your Grandma's old radio; it's a new wave of discipline function myFunction() { "use strict"; // Code follows the rules here }
Working with Linting tools
Those using JSLint or JSHint can let the linter know it's okay with simple directives:
- For JSLint: Use
/*jslint node: true */
to enable node behavior. - And for JSHint: Add
/*jshint strict:false */
to mute strict mode warnings or setnode:true
in your.jshintrc
file.
Module encapsulation
For Modular coding in many systems like ES6 modules or Node.js, strict mode comes out of the box. So, wrap your code into a module export:
You've now got a tidy module, following the rules of strict mode, but still playing nice with wider communities.
Linting configuration files
Working with .jslintrc
or .jshintrc
files allows you to tell linters to chill when it comes to 'use strict'
:
This gives a higher-level agreement on strict rules, navigating away from having to set directives in all scripts.
Where should I enforce strict mode?
Major use-cases
Where should I apply strict mode? Everywhere? Well, it depends on your intentions:
- In Libraries: Wrap it in the function around module exports to keep it to yourself.
- For Applications: Apply it at the top of your IIFEs or modules to keep things tidy and deal with issues upfront.
- Node.js code: It's already there in every module, so you don't need to sweat!
By keeping 'use strict'
within its own scope, you dodge global conflicts and uphold compatibility.
Leveraging Linting tools
Linting tools like ESLint provide nuanced control via configuration options. Build tools like Grunt/gulp can automate the good practice of enforcing 'use strict'
during your build process.
Knowing the consequences
But, remember: strict mode can't be undone within the same function or script. So, understand your JavaScript environment and test after every change with tools like grunt jshint
.
Was this article helpful?