Skip to content Skip to sidebar Skip to footer

"use Strict" Inheritance / Scope

//Global Scope 'use strict'; //1 function A() { 'use strict'; //2 function innerA() { 'use strict'; //3 } } I was just wondering: Is doing use strict at //1

Solution 1:

Quoting MDN on strict mode,

To invoke strict mode for an entire script, put the exact statement "use strict"; (or 'use strict';) before any other statements.

concatenating strict and non-strict scripts is problematic. It is thus recommended that you enable strict mode on a function-by-function basis.

So putting it at the top applies to the entire file. You don't have to explicitly mention that in every function.

Note: Using use strict at the top has its own problems. Read about them in the linked MDN page. So, the recommended approach, as per MDN is

You can also take the approach of wrapping the entire contents of a script in a function and having that outer function use strict mode. This eliminates the concatenation problem but it means that you have to explicitly export any global variables out of the function scope.


You can test that, like this

'use strict';

(function () {
    return {
        1: 1,
        1: 2
    };
})();

Now, it will throw an error,

SyntaxError: Duplicate data property in object literal not allowed in strict mode

But, when you do something like this

(function () {
    return {
        1: 1,
        1: 2
    };
})();

(function () {
    'use strict';
    return {
        1: 1,
        1: 2
    };
})();

it will fail only in the second function, not in the first function. Because, only the second function is in strict mode.

Also, if you had a function within a function, like you have shown in the question,

(function () {
    'use strict';
    (function () {
        return {
            1: 1,
            1: 2
        };
    })();
})();

the inner function will also be in the strict mode because of the use strict in the enclosing function. So, the inner function will raise a SyntaxError.


But, if you use use strict in a block within {}, it will not have any effect, for example,

(function () {
    {
        'use strict';
        return {
            1: 1,
            1: 2
        };
    }
})();

or

console.log("");

'use strict';

var a = {
    1: 1,
    1: 2
};

will not throw any error.


So, use strict should be at the beginning of a function, or at the beginning of a file. Only then the code will be in strict mode.


Solution 2:

Defining it at //1 is enough. This is straight from JavaScript: The Definitive Guide (with emphasis added by me):

The top-level (nonfunction) code of a script is strict code if the script has a "use strict" directive. A function body is strict code if it is defined within strict code or if it has a "use strict" directive.


Post a Comment for ""use Strict" Inheritance / Scope"