The first thing to study is the building blocks of the code.
Statements
Statements are syntax constructs and commands that perform actions.
We’ve already seen a statement
alert('Hello, world!')
, which shows the message.
We can have as many statements in the code as we want. Another statement can be separated with a semicolon.
For example, here we split the message into two:
alert('Hello'); alert('World');
Usually each statement is written on a separate line – thus the code becomes more readable:
alert('Hello');
alert('World');
Semicolons
A semicolon may be omitted in most cases when a line break exists.
This would also work:
alert('Hello')
alert('World')
Here JavaScript interprets the line break as an “implicit” semicolon. That’s also called an automatic semicolon insertion.
In most cases a newline implies a semicolon. But “in most cases” does not mean “always”!
There are cases when a newline does not mean a semicolon, for example:
alert(3 +
1
+ 2);
The code outputs
6
, because JavaScript does not insert semicolons here. It is intuitively obvious that if the line ends with a plus "+"
, then it is an “incomplete expression”, no semicolon required. And in this case that works as intended.
But there are situations where JavaScript “fails” to assume a semicolon where it is really needed.
Errors which occur in such cases are quite hard to find and fix.
0 comments:
Post a Comment