Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 752
Deepak Patil Avatar asked May 07 '12 10:05

Deepak Patil


People also ask

When would you not use strict mode?

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.

Do JavaScript modules automatically use strict mode?

Strict mode for modulesThe entire contents of JavaScript modules are automatically in strict mode, with no statement needed to initiate it.

Should I enable strict mode?

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.

Do modules always use strict mode?

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.


2 Answers

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 
like image 149
ThiefMaster Avatar answered Sep 20 '22 06:09

ThiefMaster


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.

like image 39
noseratio Avatar answered Sep 21 '22 06:09

noseratio