Working in strict mode

Let's start with a change that you probably won't need! JS was somewhat cavalier as to some errors and, instead of warning or crashing, it would just silently ignore them. In 2015, a new strict mode was included, which changed the JS engine's behavior to start reporting these errors. To enable the new mode, you had to include a single line before anything else, with a simple string:

"use strict";

Including this string would enforce strict mode for your code. What errors were caught? A brief list includes the following:

  • You cannot create a global variable by accident. If you misspelled a variable's name in a function, JS would have created a new global variable and just moved on; in strict mode, an error is produced.
  • You cannot use eval() to create variables.
  • You cannot have function parameters with duplicate names, as in function doIt(a, b, a, c).
  • You cannot delete non-writable object properties; for example, you cannot delete someObject.prototype.
  • You cannot write to some variables; for instance, you cannot do undefined=22 or NaN=9.
  • The with statement is forbidden.
  • Some words (such as interface or private, for example) were reserved for keywords in future versions of JS.
The previous list isn't complete and there're a few more changes and restrictions. For full details, read https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode.

Should you use this? For your main script, "use strict" is optional, but for modules and classes, it's implied. So, most code will always run in strict mode, so you'd really get used to including that string. That said, if you are using Babel, the required string is already provided for you by the transpiler. On the other hand, Node's modules will require it, as we'll see in the next chapter.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.147.44.182