getify / You-Dont-Know-JS

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

A concern about the "only whitespace and comments are allowed before the use-strict pragma" part #1786

Closed SiarheiBobryk closed 2 years ago

SiarheiBobryk commented 2 years ago

"I already searched for this issue"

Edition: 2nd

Book Title: You Don't Know JS Yet: Get Started

Chapter: 1

Section Title: Strictly Speaking

Question:

The "Strictly Speaking" section says that

// only whitespace and comments are allowed
// before the use-strict pragma
"use strict";
// the rest of the file runs in strict mode

However, I'm able to run the following code without any errors/crushes in my Node.js (v16) and in Chrome as well:

// only whitespace and comments are allowed
// before the use-strict pragma
console.error('error');
const test = '';
function foo() { };
"use strict";
// the rest of the file runs in strict mode
console.info('works!');

So I have a concern about the "only whitespace and comments are allowed before the use-strict pragma" part. If that is true, why am I able to run the example above? Maybe am I missing something? Also, what is the expected behaviour if I violate the "only whitespace and comments are allowed" rule?

getify commented 2 years ago

If that is true, why am I able to run the example above? ... what is the expected behaviour if I violate the "only whitespace and comments are allowed" rule?

By "allowed" I meant "is effective". IOW, "use strict" only does something relevant if it appears at the "top" of a function or global scope, where "top" means "nothing before it except for optional whitespace or comments".

If it's not in that "top" position, it's ONLY seen as a trivial string value expression. That means it doesn't do anything. It doesn't turn on strict mode for that program/scope. But it also doesn't cause any exceptions. It's just processed, does nothing of any importance, and moves on.

Here's two screenshots to illustrate. In the first snippet, strict mode is switched on, and the program throws a syntax error on the duplicate parameters.

1

In this second snippet, strict mode does NOT get switched on, so the "use strict" just gets processed as a string value that has no other purpose or effect on the program (but is valid and legal).

2
SiarheiBobryk commented 2 years ago

Thanks for the detailed explanation @getify! And a BIG thanks for your great books ❤️