getify / You-Dont-Know-JS

A book series on JavaScript. @YDKJS on twitter.
Other
179.26k stars 33.48k forks source link

semicolon before "use strict"; pragma #1792

Closed Violet-Bora-Lee closed 2 years ago

Violet-Bora-Lee commented 2 years ago

Please type "I already searched for this issue":

Edition: 2nd

Book Title: Get started

Chapter: Ch1

Section Title: Use strict

Question: Hi, Kyle. I'm translating your book into Korean with an agent. I have a question about the warning in the image below.

image

Do you intend the situation that the code ending with ; comes before the pragma such as,

"hello world";
"use sctict";

Or just ; before pragma such as,

;
"use sctict";
getify commented 2 years ago

All of the above. Each of these scenarios is enough to invalidate the strict-mode pragma (not an error, just silently gets ignored):

var x;
"use strict";
"whatever";
"use strict";
;
"use strict";
;"use strict";
Violet-Bora-Lee commented 2 years ago

Cool. It's more understandable with the examples, especially the 4th one.

But I couldn't fully grasp the phrase, because it's valid JS to have a string literal expression in a statement position.

Do you intend that a string literal expression is "use strict";? If so, do you assume that statement can position on every line?

getify commented 2 years ago

A string literal is like "whatever" or "use strict"... those are totally valid expression statements and can appear stand-alone on any line of a program. The point being made is that "use strict" is just a plain string expression statement UNLESS it is the very first statement in a block or file, in which case it becomes the special use-strict pragma.

The reason this needs to be pointed out is that it's all-too-easy to have the "use strict" in your program/function and think you have strict mode turned on, but because of even a stray ; appearing before it, now your intended use-strict pragma is actually silently useless. There's no warning (other than linters) that says, "Hey, you use-strict pragma is wrongly positioned".

Violet-Bora-Lee commented 2 years ago

Thanks for your detailed explanation!!

I've translated the strict mode section and will add a link to this issue in the footnote for Korean readers.