"use strict"
For long time JavaScript evolved without facing compatibility issues. This is because JavaScript added new features without changing old functionality. And it had the benefits of never breaking existing code.
This case was until 2009 when ECMAScript 5 (ES5) appeared. In that version new features were added and also modified some of the existing ones. But most modifications are off by default to keep the old code working. If we want to work the whole scripts modern way we need to explicitly enable them.
For that we can use a directive looks like a string "use strict" or 'use strict'.
Always use "use strict" at top of our script file and it is recommended.
// At top of the file
"use strict";
// code
// code
//code
// code will work modern way
We can use "use strict" at the beginning of the function body instead of at the top of the script. It will enable strict mode in that function only.
// default mode
(function(){
"use strict";
// strict mode
})();
// default mode
But again it is recommended to use "use strict" at top of the file.
Top comments (2)
One thing to note is that you do not need to add
"use strict";
when writing a module (Common JS or ES Module) as it's strict by default."In the CommonJS module system, a hidden function wraps each module and limits the scope of a “global” strict mode directive.
In ECMAScript modules, which always have strict mode semantics, the directives are unnecessary." (See eslint.org/docs/rules/strict)
Thanks for sharing this.