Is there anyway to check if strict mode 'use strict' is enforced , and we want to execute different code for strict mode and other code for non-strict mode. Looking for function like isStrictMode();//boolean
If you have such an unrestrictedly typed code, that is used variables without declaring. One variable declared within some function/scope and used from somewhere else(it will be undeclared there) and you can't rewrite/change them, then you should not go for "use strict;" mode because it will break the code.
Strict mode for modulesThe entire contents of JavaScript modules are automatically in strict mode, with no statement needed to initiate it.
Strict mode makes several changes to JavaScript semantics. It eliminates silent errors and instead throws them so that the code won't run with errors in the code. It will also point out mistakes that prevent JavaScript engines from doing optimizations.
Module code is always strict mode code. All parts of a ClassDeclaration or a ClassExpression are strict mode code. Eval code is strict mode code if it begins with a Directive Prologue that contains a Use Strict Directive or if the call to eval is a direct eval (see 12.3. 4.1) that is contained in strict mode code.
The fact that this
inside a function called in the global context will not point to the global object can be used to detect strict mode:
var isStrict = (function() { return !this; })();
Demo:
> echo '"use strict"; var isStrict = (function() { return !this; })(); console.log(isStrict);' | node true > echo 'var isStrict = (function() { return !this; })(); console.log(isStrict);' | node false
I prefer something that doesn't use exceptions and works in any context, not only global one:
var mode = (eval("var __temp = null"), (typeof __temp === "undefined")) ? "strict": "non-strict";
It uses the fact the in strict mode eval
doesn't introduce a new variable into the outer context.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With