Semicolon
- A semicolon may be omitted in most cases when a line break exists.
- There are situations where JavaScript “fails” to assume a semicolon where it is really needed.
- If we run the following code, only the first alert is shown and then we have an error.
- The error in the no-semicolon variant occurs because JavaScript does not assume a semicolon before square brackets.
alert("There will be an error")
[1, 2].forEach(alert)
// Here's how the engine sees it:
alert("There will be an error")[1, 2].forEach(alert)
- It is recommended to put semicolons between statements even if they are separated by newlines.
The Modern Mode
- In 2009, ECMAScript 5 (ES5) added new features to the language and modified some of the existing ones.
- To keep the old code working, most modifications are off by default.
- You need to explicitly enable them with a special directive:
"use strict"
- When it is located at the top of a script, the whole script works the “modern” way.
- It can be put at the start of most kinds of functions instead of the whole script.
- Doing that enables strict mode in that function only.
- There is no directive that reverts the engine to old behavior.
- Several language features, like “classes” and “modules”, enable strict mode automatically.