Qix Qix - 1 month ago 6x
Javascript Question

Can comments come before `use strict;`?

I've seen a few places around the internet passively stating

'use strict;'
must come on the first line of the functional scope for which you want the behavioral directive to apply.

However, in my experience, it doesn't matter if there are comments before it.

/* some comment */
'use strict';

Is there a functional deficiency with having comments come before the directive, or is it purely a matter of style? Is this defined anywhere in the ECMAScript specification?

I'm asking not only for V8 (node.js) environments, but for browsers as well.

Qix Qix

According to the ECMAScript 262 5th edition standard section 14.1:

. . . the initial SourceElement productions of a Program or FunctionBody and where each ExpressionStatement in the sequence consists entirely of a StringLiteral token followed a semicolon

Emphasis mine

and the ECMAScript 262 6th edition standard section 14.1.1:

A Directive Prologue is . . . the initial StatementListItem or ModuleItem productions of a FunctionBody, a ScriptBody, or a ModuleBody.

Emphasis mine

Perhaps more simply put, section 7.4 of the ECMAScript 5th ed. standard (section 11.4 of the ECMAScript 6th ed. standard) states:

Comments behave like white space and are discarded

Since comments are not statements and are ultimately discarded, use strict; can come after them as it is the first effective statement in the body.