11

Nearly all my JS files are wrapped in anonymous functions. If I include "use strict"; outside the anonymous function, is strict mode still applied to the anonymous function?

For example, is strict mode applied to the inner body of the anonymous function in the script below:

"use strict";

(function() {
    // Is this code running under strict mode?
})(); 

1 Answer 1

9

According to John Resig's article, if you turn on strict mode at the top of the file, it applies to the entire file/script. So yes, that implies that it would apply within the anonymous function.

You can also add it within a function, in which case it only applies to that specific function.

Edited to add: here's the full specification. One relevant paragraph:

10.1.1 Strict Mode Code

An ECMAScript Program syntactic unit may be processed using either unrestricted or strict mode syntax and semantics. When processed using strict mode the three types of ECMAScript code are referred to as strict global code, strict eval code, and strict function code. Code is interpreted as strict mode code in the following situations:

  • Global code is strict global code if it begins with a Directive Prologue that contains a Use Strict Directive (see 14.1).
  • Eval code is strict eval code if it begins with a Directive Prologue that contains a Use Strict Directive or if the call to eval is a direct call (see 15.1.2.1.1) to the eval function that is contained in strict mode code.
  • Function code that is part of a FunctionDeclaration, FunctionExpression, or accessor PropertyAssignment is strict function code if its FunctionDeclaration, FunctionExpression, or PropertyAssignment is contained in strict mode code or if the function code begins with a Directive Prologue that contains a Use Strict Directive.
  • Function code that is supplied as the last argument to the built-in Function constructor is strict function code if the last argument is a String that when processed as a FunctionBody begins with a Directive Prologue that contains a Use Strict Directive.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.