Previously, we have already seen an example of the command:
alert('Hello World!')displays a message.
In order to add another command to the code – you can put it after the semicolon.
For example, instead of one call for
alert we will call two alerts:
As a rule, each command is written on a separate line – so the code is better to read:
In many cases, a semicolon can be omitted if there is a transition to a new line.
So it will also work:
However, it is important that “in many cases” does not mean “always”!
For example, run this code:
alert(3 + 1 + 2);
There are not many such situations, but errors that appear in this case are quite difficult to detect and correct.
Not to be unfounded, here is a small example.
This code works:
He brings in turn
2. Why it works is not important now, we will understand later.
It is important that such code will not work:
alert("There will be a mistake now") [1, 2].forEach(alert)
Only the first one will be displayed
If you put it, then everything will be fine:
alert( "There will be a mistake now" ); [1, 2].forEach(alert)
Over time, the program becomes large and complex. There is a need to add comments that explain what is happening and why.
Single-line comments begin with a double slash
//. The text is considered a comment to the end of the line:
// The command below says "Hello" alert( 'Hello' ); alert( 'World' ); // The second message is displayed separately
Multi-line comments begin with an asterisk
«/*»and end with an asterisk-slash
«*/», like this:
/* An example with two messages. This is a multi-line comment. */ alert( 'Hello' ); alert( 'World' );
All comment content is ignored. If you put the code inside
/* … */or after
//– it will not be executed.
/* Commented out the code alert( 'Hello' ); */ alert( 'World' );
In most editors, you can put a comment with a hot key, usually for single-line ones and something like for multi-line comments (you need to select a block and press a key combination). See the editor’s guide for details.Ctrl+/Ctrl+Shift+/Nested comments are not supported!
There will be an error in this code:
/* /* nested comment ?!? */ */ alert('Мир');