Lexical grammar & ASI
Read how ECMAScript treats whitespace, names, literals, comments, and line breaks, then predict when automatic semicolon insertion changes code.
- 01Tell the pieces of code apartTell tokens, white space, line breaks, and comments apart, and say how JavaScript picks the next token.
- 02Spot allowed spellingsExplain escapes and joiners in names, reserved words, underscores in numbers, hashbang lines, and trailing commas.
- 03Predict when a semicolon is addedUse the three ASI rules, keep words like return on the same line as their value, and spot lines that join the line above.
How JavaScript reads your code
The previous lesson, A tour of the abstract operations, showed named rules that run after JavaScript understands your code. This lesson starts one step earlier: how JavaScript reads the text you typed.
Your code is just a long line of characters. Before anything runs, JavaScript cuts it into small pieces. The rules for that cutting are called the lexical grammar. They sort every character into one of four kinds:
- Tokens: the words, numbers, and symbols that mean something, like
priceor+. - White space: spaces and tabs that only keep tokens apart.
- Line breaks: the end of a line. The spec calls them line terminators.
- Comments: notes for people, which JavaScript throws away.
The lesson also covers automatic semicolon insertion, or ASI. That is a short list of rules. Sometimes they add a missing semicolon ; for you while JavaScript reads the code.
const price = 3;console.log(price + 2);Line 1 stores 3 in price. Line 2 adds 2 and prints 5. The spaces keep the names and symbols apart. Both semicolons are written by hand. Through the lesson, we change one small piece of a program like this and watch what it prints.
A token is one piece of code that means something, such as price, 3, or +. JavaScript reads from left to right. At each spot, it takes the longest token it can. Some characters can start two different tokens. For example, / can mean division, or it can start a regular expression (a pattern for searching text). Then the code around it decides which one it is. The spec calls that choice the goal.
This lesson follows the official rules, called the spec. It does not show how one engine, like Chrome's, does the cutting. For that, see Scanner & tokens. You can read the rules themselves in the ECMAScript lexical grammar. The next lesson shows how JavaScript puts the tokens together into statements.
Spaces and invisible characters
White space keeps two tokens apart. It never ends a statement. White space includes:
- a normal space,
- a tab,
- U+FEFF, an invisible character called the BOM (byte order mark),
- a few other space characters from Unicode, like the no-break space.
"U+FEFF" is the character's number in Unicode, the big list of all characters. Some editors put a BOM at the start of a file. But a BOM can also sit in the middle of your code. Outside a string or comment, JavaScript treats it like a space.
constprice = 3;console.log(price);Line 1 has an invisible U+FEFF between const and price. It keeps the two tokens apart, just like a space. Line 2 prints 3. If you copy code from another file, it may hold invisible characters like this one. The code can still work, so they are easy to miss. Inside a string, the same character is part of the text, not a space.
const price = 3; /* notefor the reader */ console.log(price);Line 1 stores the price and opens a comment with /*. Line 2 closes it with */ and prints 3. JavaScript throws away everything inside the comment. But it remembers one thing: did the comment hold a line break?
- If yes, the comment counts as a line break.
- If no, the comment counts as a space.
The table below lists the things that look like spacing. Read each row as: "when JavaScript meets this, it does that."
| What JavaScript meets | What it does | Example |
|---|---|---|
| A space, a tab, or the BOM | Keeps two tokens apart. It never makes JavaScript add a semicolon. | A space between const and price |
| A line break: LF, CR, LS, or PS | Keeps two tokens apart. It can also make JavaScript add a semicolon. | The line break after return |
A // comment | JavaScript throws it away. The line break after it still counts. | // note and then a new line |
A /* */ comment | JavaScript throws it away. If it holds a line break, it counts as a line break. | /* note, a new line, and then */ |
U+FEFF is special. Most other invisible characters, the ones that only control how text is shown, do not work as spaces between tokens. You can put them inside comments and strings. Two of them can also sit inside a name. You will meet those two, called joiners, a little later.
Line breaks and comments
A line terminator is a character that ends a line. JavaScript knows four of them:
- LF (line feed), the usual line break on Mac and Linux,
- CR (carriage return),
- LS (line separator, U+2028),
- PS (paragraph separator, U+2029).
Windows ends lines with CR and then LF. JavaScript counts that pair as one line break. A line break does more than a space. It can make JavaScript add a semicolon, which you'll see later in the lesson. And some spots in the rules are marked [no LineTerminator here], which means "no line break allowed here".
const price = 3;console.log(price + 2);Line 1 stores 3. Line 2 starts a print call. Line 3 adds 2 and closes the call. It prints 5. A line break in the middle of this addition is fine. JavaScript does not add a semicolon just because the code moves to a new line.
const note = 'a b';console.log(note.length);Line 1 stores a string with a real tab between a and b. Line 2 prints 3, the string's length. Inside a string, a space or tab is part of the text. It does not keep tokens apart there.
const line = 'tea
milk';console.log(line.length, line.includes('
'));Line 1 has a real U+2028 (LS) between tea and milk. Line 2 prints 8 true. So the string is 8 characters long, and the LS is one of them.
- Since 2019 (ES2019), LS and PS may sit inside a quoted string as they are.
- LF and CR may not. To break a quoted string over two lines, end the line with a backslash
\. That backslash and the line break add nothing to the text.
Comments and line breaks work together like this:
- A
//comment stops just before the end of its line. The line break after it still counts. - A
/* ... */comment with a line break inside counts as a line break.
This matters for return later in the lesson. A comment can't hide a line break that is inside it.
Names and Unicode escapes
A name in code, like price or cart, is called an identifier. The rules for which characters a name may use are simple:
- The first character can be a letter from any language,
$, or_. - After that, digits and a few joining marks are allowed too.
The spec calls a name that follows these rules an IdentifierName. Later, other rules check whether that name may be used in that spot. What counts is the exact characters in the name, not how it looks on screen.
const café = 3;console.log(café);Line 1 makes a variable called café with the value 3. Line 2 reads the same spelling and prints 3. Careful: Unicode can store é in two ways, as one character or as e plus an accent mark. The two names look the same to you, but JavaScript sees two different names.
const c\u0061rt = 3;console.log(cart);A Unicode escape writes a character by its number, like \u0061 for the letter a. Line 1 uses it inside the name, so the variable is called cart. Line 2 reads cart with no escape and prints 3. The backslash is not part of the name. JavaScript turns the escape into one letter.
An escape does not get around the rules. It can't put a digit at the start of a name. It can't hide a reserved word either; you'll see that in the next section.
const tea\u200Ccup = 3;console.log(tea\u200Ccup);Line 1 puts U+200C, written as the escape \u200C, between tea and cup. U+200C is an invisible character called the zero-width non-joiner, or ZWNJ. Line 2 reads the same name and prints 3. Its partner, U+200D, the zero-width joiner or ZWJ, is allowed in the same places.
- A joiner may sit inside a name, after the first character.
- A joiner may not start a name.
- A joiner is not a space, so it can't keep two tokens apart.
In your own app, use plain names. These rules help you understand why some pasted names work but look strange. The next section is about a different question: may this name be used in this spot?
Reserved words and special words
Some words belong to JavaScript itself. There are two kinds:
- A reserved word, like
returnordefault, can never be a variable name. It can still be a property name after a dot, likecart.default. - A contextual keyword, like
async, is special only in some spots. Everywhere else it is a normal name. Soasynccan be a variable name.
const async = "tea";const cart = { default: async };console.log(cart.default);Line 1 makes a variable called async that holds "tea". Line 2 makes an object with a property called default and puts that value in it. Line 3 prints tea. Here async does not start an async function. And default is only a property name, not a variable.
const \u0065lse = 3;console.log("unreachable");Line 1 tries to write else with its first letter as an escape. JavaScript turns the escape back into e, sees else, and stops with a SyntaxError. A SyntaxError means the code breaks the writing rules, so none of it runs. Line 2 never prints.
Two more words depend on where they are:
awaitcan't be a name inside a module or inside an async function.yieldcan't be a name inside a generator function or in strict mode.
Strict mode, the stricter set of rules turned on by "use strict" or by modules, also blocks a few more names. The table below sorts names into three kinds. Read each row as: "this kind of name means this, for example this."
| Kind of name | What it means | Example |
|---|---|---|
| A name with allowed characters | Its characters follow the rules. It can always be a property name after a dot. | default in cart.default is fine. |
| A name you can use as a variable | Its characters follow the rules, and it is not a reserved word in this spot. | const price = 3 works. const default = 3 is a SyntaxError. |
| A word that is special only in some spots | Everywhere else, it is a normal name. | async can be a variable name. |
So a name passes two checks. First: are its characters allowed? Second: may it be used in this spot? A word like default passes the first check but fails the second as a variable name. Next come literals. Their spelling can also change without changing the value.
Literals and underscores in numbers
A literal is a value written straight into your code. Some examples:
- a number, like
3, - a string in quotes, like
"tea", - a regular expression between slashes, like
/tea/.
In a long number, you may put an underscore _ between digits. It is called a numeric separator. It makes big numbers easier to read, like the comma in 1,000. It does not change the value.
const price = 1_000;console.log(price + 2);Line 1 stores one thousand in price. Line 2 adds 2 and prints 1002. The underscore is part of the number 1_000. It is not an operator, and it adds nothing.
const cart = 0b1010;const total = 10n;console.log(cart, typeof total);Line 1 writes a number in binary. The 0b at the start means "binary", so 0b1010 is 10. Line 2 makes a BigInt, a whole number with no size limit; the n at the end marks it. Line 3 prints 10 bigint. The word typeof gives the type of a value as text.
The underscore only works in numbers you write in code. Strings have their own rules. For example, Number("1_000") turns the text into a number, but it gives NaN ("not a number").
const price = 1__000;console.log(price);Line 1 breaks the rule, so line 2 never runs. An underscore must sit between two digits. So it can't go:
- next to another underscore, like
1__000, - at the start or end of the number, like
1_, - next to a decimal point, like
3_.5, - next to the
eof an exponent, like1e_3, - right after a prefix such as
0x, like0x_FF.
Each of these is a SyntaxError. The lesson's tests check them without running them on this page.
When JavaScript adds a semicolon
Many people think JavaScript puts a semicolon at the end of every line. It does not. Automatic semicolon insertion (ASI) adds one in only three cases. Here is the first one.
Rule 1: a token that doesn't fit. JavaScript reads tokens one by one. Sometimes the next token can't continue the statement it is reading. The spec calls that token the offending token. Then JavaScript adds a semicolon before it, but only if one of these is true:
- there is a line break before the offending token,
- the offending token is a closing brace
}, - the semicolon would end a
do...whileloop, right after its closing).
const price = 3+ 2console.log(price)Line 1 starts making price with 3. Line 2 continues it with + 2, because a plus can follow a number. Line 3 starts with console, which can't follow 3 + 2. So JavaScript adds a semicolon before line 3, and the code prints 5. No semicolon goes before the plus.
console. So price is 5.This replays the lesson's real code. It does not show the inside of the JavaScript engine.
script
+ 2console.log(price)The replay above steps through the lesson's real addition. It does not show the engine reading tokens. Step through it to see the stored value and what gets printed. Now the other two rules:
- Rule 2: the end of the code. When the code ends and the last statement has no semicolon, JavaScript adds one there.
- Rule 3: a line break where none is allowed. Some spots in the rules say
[no LineTerminator here]. If you put a line break there, JavaScript adds a semicolon before the next token. The next section shows what that does.
console.log(3)This one line has no semicolon at the end, and it still prints 3. Rule 2 adds the semicolon.
ASI also has limits. It never adds a semicolon that would make an empty statement, a statement with nothing in it. And it never adds the two semicolons inside a for (...) loop header. You must always write those.
The table below sums up the three rules. Read each row as: "this rule adds a semicolon when this happens, for example here."
| Rule | When JavaScript adds a semicolon | Example |
|---|---|---|
| Rule 1: a token that doesn't fit | Before the next token, when it can't continue the statement and a line break comes before it. Also before a closing }, and at the end of a do...while loop. | const price = 3, then console.log(price) on the next line |
| Rule 2: the end of the code | At the very end, when the last statement has no semicolon. | A last line console.log(3) with no semicolon |
| Rule 3: a line break where none is allowed | Right after a word like return, when a line break comes next. | return, then price on the next line |
Words that need the rest on the same line
Some rules in the spec have a spot marked [no LineTerminator here]. That means "no line break allowed here". The spec calls such a rule a restricted production. You meet these spots right after these words:
return,throw, andyield,breakandcontinue.
If you put a line break there, JavaScript ends the statement at the break. What happens next depends on the word. A return with nothing after it is fine inside a function. A throw with nothing after it is a SyntaxError.
function receipt() { const price = 3; return void price;}console.log(receipt());Line 1 starts the function receipt. Line 2 stores 3 in price. Line 3 has return and then a line break. So JavaScript adds a semicolon right after return, and the function returns nothing, which is undefined.
Line 4 becomes its own statement, and it never runs. (void works out a value and throws it away; here it doesn't matter.) Line 6 prints undefined, not 3.
return ends the statement, so the next line is never returned. Right: with the value on the same line, the function returns 3.This replays the lesson's real code. It does not show the inside of the JavaScript engine.
script
function receipt() { const price = 3; return void price;}A teacher writes "Pay the shop:" on one line of a notebook. On the next line she writes "3". A helper reads the first line, pays nothing, and moves on. The "3" looks like a new note, not part of the first one.
- In real life: One notebook line holds one instruction
- In JavaScript: The line with
returnis a whole statement - In real life: The next line is a new entry
- In JavaScript: The next line is a new statement
- In real life: The amount must go on the same line
- In JavaScript: The value to return must go on the
returnline
let score = 3;score++score;console.log(score);++ adds 1. Written after a name, like score++, it is called postfix. Written before a name, like ++score, it is called prefix. A postfix ++ must be on the same line as its name.
Line 1 sets score to 3. Line 2 only reads score and does nothing with it. Line 3 is a prefix ++score, so it adds 1. Line 4 prints 4. The same goes for --.
Arrow functions have a similar rule. A line break before the arrow => is a SyntaxError.
const show = (price)=> price;console.log(show(3));Line 1 ends with the brackets (price). Line 2 starts with =>, which can't join them across the line break. So the code is a SyntaxError, and nothing prints.
async has a rule like this too. To make an async function, async must be on the same line as what follows it: function, a name, or (. If a line break comes after it, async is just a normal name.
function receipt() { throw new Error("missing");}Line 2 has throw with nothing after it, and that is not allowed. Line 3 can't fix it from the next line. The other words work like this:
breakandcontinueneed their label, if they have one, on the same line.yieldalone on a line yields nothing. The next line becomes a separate statement.
The habit is simple: keep the value or label on the same line as the word.
Lines that continue the line above
Remember Rule 1: JavaScript adds a semicolon only when the next token can't continue the line above. So when the next token can continue it, no semicolon is added. The two lines become one.
A line that starts with ( is the classic case. To JavaScript, brackets right after a value mean "call it". If that value is a number, you get a TypeError. That is an error while the code runs, not a SyntaxError.
const price = 3(function addFee() { return 2; })()console.log(price);Line 1 ends with 3 and no semicolon. Line 2 starts with (, so JavaScript reads it as a call of that 3. It is like writing 3(...). A number is not a function, so this throws "TypeError: 3 is not a function". Line 3 never prints. A semicolon after line 1 keeps the two lines apart.
(, so it joins line 1 and tries to call the number 3. Right: a semicolon after 3 keeps the lines apart.const price = 3(function addFee() { return 2; })()console.log(price);TypeError: 3 is not a functionLine 2 starts with (, so it joins line 1. JavaScript tries to call the number 3, and that throws a TypeError. Line 3 never runs.
The checkbox changes only one character in the code: the semicolon after 3. Reset takes the semicolon away again. The result panel shows what each version does. Edit & run on the code runs it for real.
const price = 3;(function addFee() { return 2; })();console.log(price);Line 1 ends with a semicolon. Line 2 calls its own function, which returns 2 but prints nothing. Line 3 prints 3. The semicolon doesn't change price. It only marks where line 1 ends.
A slash / is another tricky start, because it has two jobs:
const price = 6 / 2;const hasTea = /tea/.test("tea");console.log(price, hasTea);Line 1 uses / to divide, and gets 3. Line 2 uses slashes around tea to make a regular expression. Its test method checks the text "tea" and gives true. Line 3 prints 3 true.
How does JavaScript know which job a slash has? It looks at what came before. After a value, like 6, a slash means division. Where a new value should start, like after =, it starts a regular expression. The spec names these two modes InputElementDiv and InputElementRegExp. A slash at the start of a new line is not always a regular expression. After a value on the line above, it means division.
The table below lists the starts to watch for. Read each row as: "a line starting with this can join the line above like this, so do this instead."
| The new line starts with | How it can join the line above | What to do if you meant a new statement |
|---|---|---|
( | It calls the value above, as if it were a function. | End the line above with ;. |
[ | It reads a property of the value above. | Put ; before the [. |
| A backtick | It calls the value above, with the template string as its input. | Put ; before the backtick. |
+ or - | It adds to or subtracts from the value above. | End the line above with ;. |
/ | It can divide the value above, instead of starting a regular expression. | Put ; before the regular expression. |
The habit is simple. If a line starts with (, [, a backtick, +, -, or /, make sure the line above ends with ;. Or put a ; at the start of the new line.
Hashbang lines and trailing commas
A hashbang comment is a first line that starts with #!. JavaScript throws it away, like any comment. It is only allowed at the very start of a file. A #! anywhere later is a SyntaxError.
Why have it? When you run a file from a terminal, the system reads this line to find the program that should run the file, for example Node.
#! sample scriptconsole.log("tea");Line 1 is the hashbang, and it prints nothing. Line 2 prints tea. Nothing may come before the hashbang, not even another comment. It is a special case in the reading rules, not a new operator.
A trailing comma is a comma after the last item in a list, like ["tea", "milk",].
const cart = ["tea", "milk",];const order = { price: 3, };console.log(cart.length, order.price);Line 1 makes an array with two items and a trailing comma. Line 2 makes an object with a price property and a trailing comma. Line 3 prints 2 3. The rules for arrays and objects allow these commas. They have nothing to do with ASI. A comma is not a semicolon.
const cart = ["tea",];const withHole = ["tea",,];console.log(cart.length, withHole.length);Line 1 has one item and a trailing comma, so its length is 1. Line 2 has two commas after "tea". The first comma leaves an empty slot, often called a hole. The second comma is the trailing comma. So line 3 prints 1 2. Don't count commas to get an array's length; check for empty slots between them.
Trailing commas also work in function parameters and in the values you pass to a call. JSON is different. It is a separate format, and it does not allow trailing commas.
Check a real app change
Picture a checkout page. Its code makes a list of items, and then adds one more item on a new line. Later, someone tidies the code and deletes a semicolon. Now a line that starts with [ can join the line above. JavaScript would read it as "look up a property of the value above". So mark where the new statement starts, and then check the result in the console.
const total = 3;const show = (value) => console.log(value);show(total);Line 1 stores 3 in total. Line 2 makes an arrow function, show, that prints what it gets. Line 3 calls show with total, so it prints 3. While you tidy code like this, keep (value) and => on the same line. Otherwise you get a SyntaxError.
const items = ["tea"];const count = items.length;;["milk"].forEach((item) => items.push(item));console.log(count, items.length);Line 1 makes a list with one item. Line 2 saves its length, 1, in count. Line 3 starts with a semicolon, so it is surely a new statement. It adds "milk" to the list. Line 4 prints 1 2.
A semicolon at the start of a line helps when you can't control the line above. For example, the line above may come from a tool that writes code, or from another file joined to yours.
- A space between
constandprice - U+FEFF outside a string
- LF after
return - U+2029 between statements
- The name
price - The literal
1_000
Put each example in the right group. Then read why it belongs there.
When you review code, ask three questions in this order:
- Can this line join the line above?
- Is there a line break right after
return,throw, or a similar word? - Is there an unusual spelling, like an underscore in a number or an escape in a name?
That works better than adding semicolons wherever you guess JavaScript might need them.
Common misconceptions
Don't guess what a line break does. Run the code and look at what it prints. Then ask: can the next token continue the line above? Errors tell you something too:
- A SyntaxError means the code breaks the writing rules. Nothing runs, not even the first
console.log. - A TypeError happens while the code runs. In the example where a line starts with
(, the code starts running and then fails.
const price = 3+ 2console.log(price)Line 1 starts making price. Line 2 continues it with + 2. Line 3 prints 5. JavaScript adds no semicolon before the plus. Now compare return with a line break after it. There, the line break does add a semicolon, even when a value comes on the next line (Rule 3).
- "ASI adds a semicolon at the end of every line." No. It adds one only in the three cases: Rule 1, Rule 2, and Rule 3.
- "Spaces and line breaks are the same." No. Only a line break after words like
returnorthrowends the statement there. A space does not. - "An escape makes a reserved word safe to use as a name." No. JavaScript turns the escape back into a letter first. Then it checks the whole word.
- "An underscore can go anywhere in a number." No. It must sit between two digits.
- "A slash at the start of a line always starts a regular expression." No. After a value on the line above, it means division.
- "A trailing comma is part of ASI." No. The rules for arrays, objects, and other lists allow it. A comma is not a semicolon.
One more case: a line break inside a /* ... */ comment still counts as a line break. If that comment comes right after return, the value on the next line is not returned. A comment can't hide a line break.
Practice exercises
Guess the result before you run the code. For each example, find the one character that matters: an escape, an underscore, a line break, or a semicolon you write yourself. Type your answer, then read the worked answer.
A receipt function should return the price. But someone moved the price down to the next line. Guess what the starter code prints. Then look at the fixed code.
function receipt() {
const price = 3;
return
void price;
}
console.log(receipt());function receipt() { return 3; }
console.log(receipt());The starter code prints undefined. To return 3, put the value on the same line as return, like the code above does.
A scoreboard starts at 3. Read the two lines after it the way JavaScript does. Then type the final score. Can a ++ after a name reach across a line break?
let score = 3;
score
++score;
console.log(score);let score = 3;
score
++score;
console.log(score);The starter code prints 4. Because of the line break, score on line 2 is only read. Then ++score on line 3 adds 1.
You paste a small cart example from another file. One letter in a variable name is written as an escape. Guess what the code prints. Check the real spelling of the name before you rename anything.
const c\u0061rt = 3;
console.log(cart);const c\u0061rt = 3;
console.log(cart);It prints 3. c\u0061rt and cart are the same variable name.
The checkout price is written with an underscore between its digits. Type the number that is printed. Then explain why the underscore adds nothing to the value.
const price = 1_000;
console.log(price + 2);const price = 1_000;
console.log(price + 2);It prints 1002. The underscore only makes the number easier to read. It does not change the value.
Some checkout code calls a number by mistake. The starter code is broken on purpose. Which punctuation mark keeps the two statements apart?
const price = 3
(function addFee() { return 2; })()
console.log(price);const price = 3;
(function addFee() { return 2; })();
console.log(price);Put a semicolon after 3. Now the next line is its own function call, and the last line prints 3.
Your site adds an item to a list in its own statement. Later, the line above may lose its semicolon. What would you add right before a line that starts with an array?
const items = ["tea"];
const count = items.length;
;["milk"].forEach((item) => items.push(item));
console.log(count, items.length);const items = ["tea"];
const count = items.length;
;["milk"].forEach((item) => items.push(item));
console.log(count, items.length);Write a semicolon before ["milk"]. Then the line can never join the line above, even if that line changes. The code prints 1 2.
Check your understanding
Read each code question the way JavaScript does: token by token, not line by line. Ask two questions:
- Can the next token continue the line above?
- Is there a line break right after a word like
returnorthrow?
When a choice names an error, decide which kind it is. A SyntaxError means the code never ran. A TypeError means the code ran and then failed, for example when it called a number.
Question 1 of 7What does the receipt function print?
Read the code, then predictfunction receipt() { return 3; } console.log(receipt());Choose an answer to see the explanation.
Question 2 of 7What does an underscore do in
1_000?Read the code, then predictconsole.log(1_000 + 2);Choose an answer to see the explanation.
Question 3 of 7Which kind of spacing can make JavaScript add a semicolon?
Choose an answer to see the explanation.
Question 4 of 7What does this code with async as a name print?
Read the code, then predictconst async = "tea"; console.log(async);Choose an answer to see the explanation.
Question 5 of 7What does this code print when line 2 starts with a plus?
Read the code, then predictconst price = 3 + 2 console.log(price)Choose an answer to see the explanation.
Question 6 of 7Can an escape turn a name that breaks the rules into a valid name?
Choose an answer to see the explanation.
Question 7 of 7Which describes a hashbang comment?
Choose an answer to see the explanation.
Some questions are small programs you can run. Others ask about the rules. If you pick a wrong answer, read its explanation. Then look at the matching code example again before you try once more.
Key takeaways
Before your code runs, JavaScript cuts it into pieces. Each character is one of four kinds: a token, white space, a line break, or part of a comment. To know when JavaScript adds a semicolon, learn the three rules. How the code looks on screen is not enough.
- A BOM (U+FEFF) works like a space outside strings and comments. LF, CR, LS, and PS are line breaks.
- An escape like
\u0061stands for one letter in a name. It can't make a bad name or a reserved word allowed. - An underscore in a number must sit between two digits. A hashbang
#!line may only be the very first line of a file. - JavaScript adds a semicolon in only three cases. It never adds the two semicolons inside a
for (...)header. - Keep these on one line:
returnand its value,throwand its value,breakorcontinueand its label, a name and the++or--after it, the brackets and=>of an arrow function, andasyncand what follows it. - If a line starts with
(,[, a backtick,+,-, or/, write the semicolon yourself where the statement should end.
Remember the one-liner.
A newline changes syntax only when a grammar rule makes it matter.
Coming next: Syntax, early errors & static semantics. That lesson explains the grammar shapes and checks that follow token recognition.