Search code examples
javascripttemplate-literalsuse-strict

`use strict` is not working when we use template literals


If I enclose use strict with backticks/template literals, 'use strict' is not working as expected. Can you share the reason behind it? Are there any similar exceptional statements where template literals are not going to work as expected?

`use strict`;
x = 3.14;  // Ideally it should  cause an error (as x is not defined).
alert(x);

`use strict`; // if we enclose in single quotes or double quotes
x = 3.14;    // Ideally it should  cause an error (as x is not defined).
alert(x);

Solution

  • That's because the Use Strict Directive is explicitly defined in the specification as an ExpressionStatement consisting entirely of a StringLiteral production, and limits the exact code point sequences to be either "use strict" or 'use strict'.

    From the ECMAScript 2020 Language Specification:

    14.1.1 Directive Prologues and the Use Strict Directive

    A Directive Prologue is the longest sequence of ExpressionStatements occurring as the initial StatementListItems or ModuleItems of a FunctionBody, a ScriptBody, or a ModuleBody and where each ExpressionStatement in the sequence consists entirely of a StringLiteral token followed by a semicolon. The semicolon may appear explicitly or may be inserted by automatic semicolon insertion. A Directive Prologue may be an empty sequence.

    A Use Strict Directive is an ExpressionStatement in a Directive Prologue whose StringLiteral is either of the exact code point sequences "use strict" or 'use strict'. A Use Strict Directive may not contain an EscapeSequence or LineContinuation.

    A Directive Prologue may contain more than one Use Strict Directive. However, an implementation may issue a warning if this occurs.

    Emphasis added

    On the other hand, a TemplateLiteral is an entirely different production than a StringLiteral, and therefore cannot be a valid directive.