Strict mode was introduced in ECMAScript 5. It’s a way to tell the browsers to run the code in a variant of JavaScript. The non-official term for the opposite of Strict mode is sloppy mode.
Strict mode has different semantics from the normal JavaScript code.
Be careful while using strict mode. If any browser or a particular browser version don’t support it then you might see unexpected output.
We can also use Strict mode code and non-strict mode code together.
What does the strict mode do?
When you change the JavaScript code to strict mode, it will make few changes to the JavaScript semantics.
First, it converts silent error to throw errors. If there are code mistakes then it makes difficult for JS engines to perform optimizations. Strict mode fixes those mistakes. We can make code run faster in strict mode rather than a sloppy mode.
How to apply the strict mode?
We can apply the strict mode to either entire script code or just to an individual function. modules use strict mode automatically .
strict mode doesn’t apply to block statements in {} braces.
What happens when we try to apply strict mode to block statements?
It won’t affect the code at all. It does nothing!
These are the entire scripts where strict mode works as expected.
- eval code,
- Function code,
- event handler attributes,
- strings passed to WindowTimers.setTimeout(), and
- related functions
How to apply Strict mode to scripts?
To apply strict mode for an entire script code, we can use the exact statement “use strict”; (or in single column ‘use strict’;) before any other code starts. So, at the top of the script code is the best place for it.
Add “use strict” to apply strict mode to an entire script.
"use strict";
var msg = "strict mode on";
console.log(msg);
//strict mode on
If you want to concatenate scripts then try to use script mode at function level rather than at script level. Concatenating strict script and sloppy script creates conflict in some cases.
How to apply Strict mode to functions?
Same exact way we did at script level. The difference is that we need to add the “use strict” statement in the function before any other statements.
Just like this:
function strictModeOn() {
'use strict';
return "strict mode is ON for me";
}
function strictModeOff() {
return "strict mode is OFF for me";
}
We can add nested functions in the strict mode and they all will use strict mode.
How to apply Strict mode to modules?
The JS modules (introduced in ES 2015) use the strict mode automatically. So, you don’t need to add the “use strict” statement.
browsers code strict