Sahand
Sahand

Reputation: 8360

What happens when you combine "use strict"; inside functions with "use strict"; in the global context?

<!DOCTYPE html>
<html>
<body>
    <script>
        function useStrict(){
            "use strict";
        }
            "use strict";
            foo=10;
            alert(foo);
    </script>
</body>
</html>

Leads to no error. Conclusion: strict mode isn't activated. But if I remove the function definition:

<!DOCTYPE html>
<html>
<body>
    <script>
            "use strict";
            foo=10;
            alert(foo);
    </script>
</body>
</html>

I get an error. Conclusion: strict mode is activated. But if I remove the "use strict" line in the global context and keep the function:

<!DOCTYPE html>
<html>
<body>
    <script>
        function useStrict(){
            "use strict";
        }
        foo=10;
        alert(foo);

    </script>
</body>
</html>

I get no error. Conclusion: strict mode isn't activated. What is going on here?

It seems that when "use strict"; is both in the global context and in a function, they cancel out, since when I remove the function, strict mode is indeed activated. But then, without the "use strict"; line in the global context, but inside of the function, strict mode isn't activated, which to me is unexpected. How could they cancel out before if "use strict"; inside of a function call doesn't activate strict mode on its own?

Upvotes: 0

Views: 92

Answers (1)

Ry-
Ry-

Reputation: 224942

Your first script, for context:

function useStrict() {
    "use strict";
}

"use strict";
foo = 10;
alert(foo);

"use strict" only has an effect at the top of a script. The function useStrict() before it makes it not at the top. If you move it to the top, it will work.

"use strict";

function useStrict() {
    "use strict";
}

foo = 10;
alert(foo);

Otherwise it has the same semantics as "use mayonnaise".

Upvotes: 1

Related Questions