javascriptecmascript-5ecma262strict-mode

Is there any way to check if strict mode is enforced?


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


Solution

  • 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