completefrontend
Open lab My progress
THE JAVASCRIPT FIELD GUIDE

Syntax, early errors & static semantics

Read ECMAScript grammar rules, trace early errors and static semantics, and see why some JavaScript scripts fail before their first statement runs.

By the end, you can
  • 01
    Read a grammar ruleRead a rule from the spec: its parts, optional parts, settings, lookahead marks, and places where a line break is not allowed.
  • 02
    Tell when code failsTell an early error, which stops the whole script before it starts, from a runtime error, which happens while the code runs.
  • 03
    Use the name checksExplain what BoundNames, VarDeclaredNames, and the parameter checks find in the written code.

What JavaScript checks before code runs

Before JavaScript runs a script, it reads the whole file and checks that the code is built correctly. The rules for how code is built are called the syntactic grammar.

In the previous lesson, Lexical grammar & ASI, JavaScript cut the text into small pieces called tokens: words like let, names like price, numbers, and symbols like =. This lesson is about the next step: the rules that join tokens into bigger pieces.

  • An expression is a piece that gives a value, like 3 or cart.tea.
  • A statement is one instruction, like let price = 3;.
  • A script or a module is a whole file of statements.

Every browser builds its own reader for code. They are all built differently inside, but they must accept and reject exactly the same code.

A small program that is built correctlyPop out in the code editor (opens in a new tab)JavaScript
const cart = { tea: 3 };console.log(cart.tea);

Line 1 makes a cart object with a tea property set to 3. Line 2 reads that property and prints 3. But before line 1 can run, JavaScript must check the whole file. The file must follow the grammar and a few extra rules.

The main idea

An early error is a mistake JavaScript finds while checking the file, before any line runs. When it finds one, no line of that file runs at all.

Static semantics are the extra rules about written code. "Static" means they look at the text only, without running it. They include the early-error rules, and small checks that list the names your code declares.

This lesson builds on How to read ECMAScript. That lesson followed how a property read runs. Here we ask a question that comes first: is this code allowed to run at all? We read the rules from the language specification (the official rule book for JavaScript), not from one browser's code. To see how engines build their readers, see Parsing and ASTs and Lazy parsing.

Read a grammar rule

The specification writes each grammar rule as one line. This kind of line is called a production. A production says what one kind of code is made of:

  • On the left is a name for that kind of code, like WhileStatement. This name is called a nonterminal.
  • Then comes a colon. It means "is made of".
  • On the right are the parts, in order. A part is either a token written exactly, like while, or another nonterminal.

Grammar rules for joining tokens use one colon. The rules from the previous lesson, which build tokens out of letters, use two colons.

A variable with a starting valuePop out in the code editor (opens in a new tab)JavaScript
let price = 3;console.log(price);

Line 1 declares price and gives it the starting value 3. Line 2 prints 3. In the spec, this line is described with names like BindingIdentifier (the new variable's name) and Initializer (the = 3 part). These are names for parts of the code. They are not functions you can call.

Three grammar rules from the specText
VariableStatement : var VariableDeclarationList ;
VariableDeclaration : BindingIdentifier Initializer[+In]opt
WhileStatement : while ( Expression ) Statement

Read line 3 out loud: the word while, an opening bracket, an expression, a closing bracket, then a statement. Code must have those five parts in that order to be a while statement.

In line 2, the small opt at the end of Initializer means "optional": the = 3 part may be left out. These three lines are picked from the spec. They are not the full grammar, and they are not JavaScript you can run.

The grammar rule for a while statement split into five parts: the word while, an opening bracket, an Expression slot, a closing bracket, and a Statement slot.while(Expression)Statementexact wordany expressionany statement
The rule for a while statement has five parts. The word while and the two round brackets are written exactly. The parts Expression and Statement are slots that your own code fills in.

The table lists five marks you will see in grammar rules. Each row shows a mark, what it means, and how it is used.

Five marks used in grammar rules
The markWhat it meansHow it is used
Statement : ...One colon: a rule that joins tokens.It says which tokens, in which order, make a statement.
Identifier :: ...Two colons: a rule that builds one token from letters.It says which letters make a name like price.
Initializer[+In]optA setting plus an optional part.The = 3 part may be left out. If it is there, the in operator is allowed inside it.
[lookahead not in ...]Some tokens may not come first here.An expression statement may not start with {, function, class, or let [.
[no LineTerminator here]No line break is allowed at this spot.throw must have its value on the same line.

The grammar starts from one of two top names: Script (a normal script file) or Module (a file loaded as a module). The same token can follow different rules in each one.

When the spec reads code with these rules, it gets parse nodes. A parse node is the spec's name for one matched piece of code. Browsers do not have to store parse nodes in any special way. You can read more in the spec's section on the syntactic grammar.

Some rules change with where the code sits

Some grammar rules have a setting in square brackets, like [Yield]. This is called a grammar parameter. It switches part of the rule on or off, depending on where the code sits. There are four of them:

  • [Yield] is on inside a generator function (a function written function* that can pause).
  • [Await] is on inside an async function and inside a module.
  • [In] controls whether the in operator is allowed. It is switched off in one part of a for loop's brackets, where in has another job.
  • [Return] is on inside a function body. That is why return works in a function but not at the top of a normal script.
Inside a generator, yield pauses the functionPop out in the code editor (opens in a new tab)JavaScript
function* orders() {  const order = yield "tea";  console.log(order);}const list = orders();console.log(list.next().value);list.next("cake");

Line 1 makes a generator function. Line 2 hands out "tea" with yield and pauses there. Line 3 will print whatever value is sent back in later.

Line 5 creates the generator. Line 6 runs it up to the pause and prints tea. Line 7 sends in "cake", so line 3 prints cake. The output is tea, then cake.

The in operator in a normal expressionPop out in the code editor (opens in a new tab)JavaScript
const cart = { tea: 3 };console.log("tea" in cart);

Line 1 makes a cart with a tea property. Line 2 asks whether the cart has a property called tea, and prints true.

The spec marks the [In] setting with three signs:

  • +In means "the in operator is allowed here", like in line 2.
  • ~In means "not allowed here". It is used where in would clash with a for loop.
  • ?In means "keep whatever setting the outer rule had".

The Yield and Await settings also decide which names you may use. Inside a generator, you cannot name a variable yield. Inside an async function, you cannot name a variable await. In a module, you cannot name a variable await anywhere. The spec's rules for names list every case.

await cannot be a variable name herePop out in the code editor (opens in a new tab)JavaScript
console.log("before");
async function total() {
  let await = 3;
}
yield cannot be a variable name herePop out in the code editor (opens in a new tab)JavaScript
console.log("before");
function* total() {
  let yield = 3;
}
await as a name in a module, to read onlyJavaScript
console.log("before");
const await = 3;

Line 1 of each of these three examples asks to print before. Nothing prints, because the file is rejected before it starts.

The last example only fails when the file is loaded as a module, so it has no Edit & run button. The lesson's tests run it as an .mjs file (a module file). These rules depend on where the name sits. There is no single list of names that are banned everywhere.

Optional parts and looking ahead

You already met opt: it marks a part of a rule that may be left out. It has nothing to do with JavaScript's ?. operator (optional chaining).

A lookahead rule is a different mark. It says which tokens may not come first at that spot. It is needed because some code could be read in two ways. For example, a line that starts with { could be a block of statements or an object. The lookahead rule settles it: a statement that starts with { is always read as a block.

A line that is just an expressionPop out in the code editor (opens in a new tab)JavaScript
const order = 3;console.log(order);

Line 1 makes order with the value 3. Line 2 is a function call used on its own as a statement. It prints 3.

A statement that is just an expression, like line 2, is called an expression statement. A function call is allowed to start one. A few other starts are blocked, so that JavaScript never mixes up an expression statement with a block or a declaration.

The lookahead rule, simplifiedText
ExpressionStatement : [lookahead not in { {, function, class, let [ }] Expression ;

This line is a simpler version of the rule, written for this lesson. It is not copied word for word from the spec. Read it like this: an expression statement is an expression and a semicolon, but it may not start with:

  • {, because that starts a block;
  • function or class, because those start declarations;
  • let [, because that starts a let declaration.

The exact rule is in the spec's section on expression statements.

Real-life analogyA school attendance register

A teacher's register has one row per child. Each row starts with a name, then a space for a mark. A blank mark does not remove the name from the row. When the teacher sees the next name, she knows a new row has started.

In real life: Each row starts with a name
In JavaScript: Each piece of code starts with a token
In real life: The mark beside a name may be blank
In JavaScript: An opt part may be left out
In real life: A new name means a new row
In JavaScript: Looking at the next token tells JavaScript what comes next

An early error stops the whole script

Following the grammar is not enough. After the code is read, the spec checks it against a list of early error rules. If one rule fails, the whole file is rejected before it runs. So a mistake on line 3 can stop a console.log on line 1 from printing.

This only stops that one script or module. Other scripts on the same page still run.

One let declaration runs finePop out in the code editor (opens in a new tab)JavaScript
let price = 3;console.log(price);

Line 1 makes price and sets it to 3. Line 2 prints 3. Now keep a print on line 1, and declare price with let twice in the same place.

Two let declarations stop the whole scriptPop out in the code editor (opens in a new tab)JavaScript
console.log("before");let price = 3;let price = 4;console.log("after");

Line 1 asks to print before, but nothing prints. Lines 2 and 3 both declare price with let. That breaks an early error rule, so JavaScript rejects the whole script before line 1 runs. Line 4 never runs either.

The lesson's test checks this for real. It saves the code to a file, runs it with Node.js, and checks two things: the error is a SyntaxError, and nothing was printed.

A runtime error happens laterPop out in the code editor (opens in a new tab)JavaScript
console.log("before");try {  missingPrice();} catch (error) {  console.log(error.name);}

Compare a mistake that JavaScript only finds while the code runs. This is called a runtime error.

  • Line 1 prints before.
  • Line 3 calls missingPrice(), a function that does not exist. This only fails when line 3 runs.
  • Line 4, the catch, catches the error.
  • Line 5 prints the error's name, ReferenceError.

So both prints appear: before, then ReferenceError. A try/catch can handle a runtime error like this one. It cannot handle an early error in its own script, because that script never starts.

Left: a script with two let price lines. Its console stays empty, because the whole script is rejected before line 1. Right: a script that calls missingPrice. Its console shows before, then ReferenceError.duplicate letConsolenothing printedrejected before line 1missing callConsolebeforeReferenceErrorfails at line 3
Left: two let price lines. JavaScript rejects the whole script, so nothing prints. Right: the script starts, prints before, and only fails when line 3 calls missingPrice().

The table compares three ways code can fail. Each row says what went wrong, why, and what you see.

Three ways code can fail, and when
What went wrongWhyWhat you see
The code does not fit the grammar.The tokens cannot be joined into a script or module, like add(3 with no closing bracket.A SyntaxError. No line of that file runs.
An early error.The code fits the grammar, but an extra rule forbids it, like two let price lines.A SyntaxError. No line of that file runs.
A runtime error.The script starts, then one line fails while running, like calling missingPrice().Lines before it have already run, so their prints show.
Compare when a problem is found
The small function behind the buttonsPop out in the code editor (opens in a new tab)JavaScript
function describeEarlyCheck(kind) {  return kind === "duplicate"    ? "reject before running"    : "run until the call fails";}console.log(describeEarlyCheck("duplicate"));
The case you pickedDuplicate let

reject before running

Try it yourself

The small function says: reject before running. The real examples above show what JavaScript does.

The buttons run the small function shown here. They do not check or run any code you type. Reset picks Duplicate let again.

Pick one case at a time, then press Reset to go back to the duplicate let case. The buttons only run the small function shown in the playground. They do not check any code you type.

This is useful when a tool reports a syntax problem, but a console.log you put above the bad line never printed. The early error stopped the whole file, including your print.

The same brackets can mean two things

Round brackets can do two different jobs. They can group a value, like (3). Or they can hold the parameters of an arrow function, like (price) => price + 2. When JavaScript reads the opening bracket, it does not know yet which job it is.

The spec solves this in two steps:

  1. First, a wide rule called a cover grammar reads the brackets. It accepts anything that could be either job.
  2. Then JavaScript looks at what comes after. That decides the job. The brackets must now also fit a stricter rule for that job, called the supplemental grammar.

The spec's long name for the wide rule is CoverParenthesizedExpressionAndArrowParameterList. It just means "brackets that might be a grouped expression or arrow parameters".

Brackets before an arrow hold parametersPop out in the code editor (opens in a new tab)JavaScript
const add = (price) => price + 2;console.log(add(3));

Line 1 makes a function called add. An arrow => comes right after the brackets, so price is a parameter. Line 2 calls add(3) and prints 5.

The same brackets group a valuePop out in the code editor (opens in a new tab)JavaScript
const price = (3);console.log(price);

Line 1 puts brackets around 3. No arrow comes after them, so they only group the value. Line 2 prints 3.

So JavaScript cannot treat every pair of brackets as parameters. What comes after decides which stricter rule they must fit. Here, the rule for grouping says the brackets must hold an expression.

A pair of round brackets with two arrows. Left: (price) => price + 2, an arrow follows, so price is a parameter. Right: (3), no arrow follows, so 3 is just grouped.( … )(price) => price + 2an arrow followsprice is a parameter(3)no arrow follows3 is just grouped
JavaScript first reads round brackets without deciding what they are. If => comes next, they hold parameters. If not, they just group a value.
A comma cannot end grouping bracketsPop out in the code editor (opens in a new tab)JavaScript
console.log("before");
const price = (3,);
console.log(price);

Line 1 never prints. Line 2 has (3,). Arrow parameters may end with a comma, like (price,) => price. But no arrow follows here, so these must be grouping brackets. Grouping brackets cannot end with a comma.

So the whole script is rejected with a SyntaxError before it runs. Line 3 is never reached. (3,) is not the same as 3.

Step through picking the job of round brackets
Step 0 of 4Ready
Your turn: follow the blue line

These are saved steps from running the lesson's small function. They are not how a browser reads code.

Running in
  1. script
Next: line 4
function chooseParenthesizedForm(hasArrow) {  return hasArrow ? "arrow parameters" : "grouped expression";}
CallStoreChangeResultBlue line: runs next. Ran: already executed.
Recent returnsNothing yet. Start with the blue line.
A guided replay recorded from real JavaScript calls, not an engine debugger. Step follows executed statements; Back reviews a snapshot. Reset starts a fresh run.

This step-through runs a tiny function from this lesson and shows its result. It only shows the idea: what comes after the brackets decides their job. It is not how a browser really reads code. A real browser checks the whole bracket contents against the stricter rule, and applies the early error rules too.

Checks that list the names your code declares

Some static rules are small checks with names. One of them is called BoundNames. It lists the names of the new variables that a declaration creates.

Like every static rule, it only reads the written code. It never looks at a running variable or its value.

This matters for destructuring: taking values out of an object into variables in one line. In destructuring, the property you read and the variable you create can have different names.

Read the key tea into a variable called pricePop out in the code editor (opens in a new tab)JavaScript
const { tea: price } = { tea: 3 };console.log(price);

Line 1 reads the tea property, which holds 3. It stores that value in a new variable called price. Line 2 prints 3.

For this line, BoundNames gives price, not tea. That is because price is the new variable, and tea is only the key that was read. BoundNames gives back names, never values: it does not give the number 3.

The code const { tea: price } = { tea: 3 }. An object holds tea: 3. An arrow carries the value 3 into a new box called price. The key read is tea; the name declared is price.const { tea: price } = { tea: 3 };tea: 3object3pricereads the key teadeclares price
The pattern reads the key tea from the object. It puts the value 3 in a new variable called price. So the name this line declares is price, not tea.
Two var declarations can share a namePop out in the code editor (opens in a new tab)JavaScript
var price = 3;var price = 4;console.log(price);

Line 1 sets price to 3. Line 2 declares price again with var and sets it to 4. Both lines use the same variable. Line 3 prints 4.

Two more named checks collect names, one for each kind of declaration:

  • VarDeclaredNames lists the names declared with var.
  • LexicallyDeclaredNames lists the names declared with let, const, and similar.

These checks only make the lists. A name that appears twice is not automatically a mistake. A separate early error rule decides which repeats are not allowed. Two var lines are allowed; two let lines are not.

const and let declare the same namePop out in the code editor (opens in a new tab)JavaScript
console.log("before");
const { tea: price } = { tea: 3 };
let price = 4;

Again, line 1 prints nothing. Line 2 declares price through destructuring. Line 3 declares price again with let. The name checks find the repeat before the script runs, so the script is rejected.

A linter (a tool that checks your code as you type) may show a friendlier message. But the rule is part of the language. It applies with or without a linter.

The table lists the five named checks in this lesson. Each row gives the check, what it looks at, and an example from this lesson.

Five named checks that read written code
The checkWhat it looks atExample from this lesson
BoundNamesThe names of the new variables a declaration creates.const {tea: price} = cart creates price, not tea.
LexicallyDeclaredNamesThe names declared with let, const, and similar.Two let price lines in the same place are an error.
VarDeclaredNamesThe names declared with var.Two var price lines are allowed. They use the same variable.
IsSimpleParameterListWhether every parameter is just a plain name.price = 3 has a default value, so the list is not simple.
ContainsUseStrictWhether the function body starts with "use strict"."use strict" in a function with a default value is an error.
Step through a check for a repeated name
Step 0 of 4Ready
Your turn: follow the blue line

These are saved steps from running the lesson's small function. They are not a real browser debugger.

Running in
  1. script
Next: line 1
function hasDuplicateName(names) {  return new Set(names).size !== names.length;}console.log(hasDuplicateName(names));
CallStoreChangeResultBlue line: runs next. Ran: already executed.
Recent returnsNothing yet. Start with the blue line.
A guided replay recorded from real JavaScript calls, not an engine debugger. Step follows executed statements; Back reviews a snapshot. Reset starts a fresh run.

This step-through uses a Set (a list that keeps each value only once) to spot a repeated name. If the Set is smaller than the list, a name appeared twice. It is a small model for this lesson. It is not the spec's BoundNames check and not a browser's real code. The lesson's tests check this function separately.

Extra rules for function parameters

Functions have a few extra early error rules. They use two more named checks:

  • IsSimpleParameterList asks: is every parameter just a plain name? A default value (price = 3), a rest parameter (...prices), or destructuring makes the answer "no". Then the list is called non-simple.
  • ContainsUseStrict asks: does the function body start with the line "use strict"? This line is a directive: it switches the function into strict mode.
A plain-name parameterPop out in the code editor (opens in a new tab)JavaScript
function total(price) {  return price + 2;}console.log(total(3));

Line 1 makes a function total with one parameter, price. It is a plain name, so the list is simple. Line 2 adds 2. Line 4 passes 3 and prints 5.

A default value makes the list non-simplePop out in the code editor (opens in a new tab)JavaScript
function total(price = 3) {  return price + 2;}console.log(total());

Line 1 gives price a default value of 3. Now the list is non-simple. Line 2 adds 2. Line 4 passes nothing, so price uses its default, and the line prints 5.

Default values are fine on their own. The next example shows the mix that is not allowed.

"use strict" in a body with a default valuePop out in the code editor (opens in a new tab)JavaScript
console.log("before");
function total(price = 3) {
  "use strict";
  return price + 2;
}

Line 1 would print before. Line 2 has a default value. Line 3 puts "use strict" in the body. Together, they break an early error rule, so the script is rejected with a SyntaxError before line 1 runs.

Note that the problem is the "use strict" line inside this function's body. A function with a default value is fine inside a module, even though a module is always strict.

An arrow function with the same parameter twicePop out in the code editor (opens in a new tab)JavaScript
console.log("before");
const total = (price, price) => price;
The same parameter twice, with "use strict"Pop out in the code editor (opens in a new tab)JavaScript
console.log("before");
function total(price, price) {
  "use strict";
  return price;
}
The same parameter twice, with a default valuePop out in the code editor (opens in a new tab)JavaScript
console.log("before");
function total(price = 3, price) {
  return price;
}

In each of these three examples, line 1 asks to print before, and nothing prints. A parameter name may not repeat in:

  • an arrow function;
  • a function with "use strict" in its body;
  • a function with a non-simple list, even without "use strict".

But an old-style function with plain names, outside strict mode, may repeat a name. So "a repeated parameter is always an error" is not true. The spec's rules for functions list every case.

Places where a line break is not allowed

Some grammar rules contain the mark [no LineTerminator here]. It means: no line break is allowed at this spot. A rule with this mark is called a restricted production. What happens when you break the line there depends on the rule:

  • After return, a line break ends the statement. JavaScript adds a semicolon for you (this is automatic semicolon insertion, or ASI). The function returns nothing.
  • After throw, a line break is an error. No semicolon can fix it.
return, then a new linePop out in the code editor (opens in a new tab)JavaScript
function receipt() {  return  3;}console.log(receipt());

Line 1 starts a function. Line 2 has return and then a line break, so the function returns right there, with no value. Line 3 is a separate statement that never runs. Line 5 calls the function and prints undefined, not 3.

throw cannot be followed by a line breakPop out in the code editor (opens in a new tab)JavaScript
console.log("before");
throw
new Error("no order");

Line 1 does not print before. Line 2 has throw with nothing after it on that line. Line 3 cannot fix that. The script is rejected with a SyntaxError before it runs. This is why adding semicolons everywhere does not fix every line-break problem.

An arrow cannot start on a new linePop out in the code editor (opens in a new tab)JavaScript
const total = (price)
  => price + 2;
console.log(total(3));

Line 1 ends with the arrow function's parameters, (price). Line 2 starts with => after a line break, and the rule forbids that. So line 3 never prints.

The spec's notes on this mark explain it: spaces are fine at these spots, but a line break is not.

Check a checkout script before blaming a function

Say a shop's checkout page suddenly shows nothing. Before you look at your functions or data, check whether the script can start at all.

  • If the script has an early error anywhere, even your first console.log will not print.
  • If the script is built correctly, it can print first and fail later, while running.

A good first step is to cut the script down to one simple read that you know works.

A simple cart read that worksPop out in the code editor (opens in a new tab)JavaScript
const cart = { tea: 3 };console.log(cart.tea);

Line 1 makes a cart where tea costs 3. Line 2 reads the property and prints 3. Next, destructuring can put that property in a variable called price. It does not create a variable called tea.

Give the property a new name without a clashPop out in the code editor (opens in a new tab)JavaScript
const cart = { tea: 3 };const { tea: price } = cart;console.log(price);

Line 1 makes the cart. Line 2 reads its tea value into a new variable, price. Line 3 prints 3.

If someone adds another let price in the same place, it does not just replace the price. The whole script is rejected before any line runs.

Here are three more early errors that are good to spot when you review code:

  • Assigning to something that cannot hold a value, like 3 = 4.
  • A break that names a label that does not exist. (A label is a name you put before a loop, like orders:.)
  • A regular expression with the same flag twice, like /tea/gg.

The examples below fail on purpose. Each one starts with a print on line 1, so you can see that nothing runs.

A number cannot be assigned toPop out in the code editor (opens in a new tab)JavaScript
console.log("before");
3 = 4;
A break needs a label that existsPop out in the code editor (opens in a new tab)JavaScript
console.log("before");
for (const order of ["tea"]) {
  break missingLabel;
}
A regex flag cannot repeatPop out in the code editor (opens in a new tab)JavaScript
console.log("before");
const pattern = /tea/gg;

Line 1 is the same print in all three. Here is what is wrong in each:

  • In the first, line 2 tries to assign to the number 3.
  • In the second, line 3 breaks to missingLabel, but no loop has that label.
  • In the third, line 2 repeats the g flag.

Each one is rejected before any print. To learn how browsers build syntax trees and readers for code, see Parsing and ASTs. This lesson is about what the language itself requires.

Which kind of check is it?
  • throw followed by a line break
  • Two let price lines in the same place
  • A regular expression written /tea/gg
  • Call missingPrice() after a print
  • Find the new variable in {tea: price}
  • Ask whether price = 3 is a plain-name parameter
Try it yourself
0 of 6 correct

Sort each case into the group it belongs to. Then read the reason on each card.

Choose a category for every card. You can change an answer at any time; Reset clears them all.

Common mistakes

The grammar and the extra rules (static semantics) both read written code, but they ask different questions:

  • The grammar asks: do the tokens fit together in a shape JavaScript knows?
  • The early error rules ask: the shape fits, but is it allowed here?

The error's name alone does not tell you when it happened. A SyntaxError is usually found before running, but some appear while running.

  • “A print above the bad line still runs.” Not if the same script has an early error. Then no line runs.
  • “A try/catch in the same script can catch any SyntaxError.” An early error stops the script before the try starts.
  • “Brackets before an arrow are just grouping brackets.” When an arrow follows, they must fit the stricter rule for arrow parameters.
  • “The extra rules are a slow extra step inside the browser.” They are rules written in the spec. The spec does not say when or how a browser checks them.
  • “Every line break adds a semicolon.” A line break after return ends the statement, but a line break after throw is an error.
  • “Any repeated name is an error.” It depends on how the name is declared (var or let), where it sits, and what kind of function it is in.

To check yourself, compare two pairs from this lesson:

  • The two let price lines (an error) and the two var price lines (allowed).
  • The line break after return (allowed) and the one after throw (an error).

Spotting a familiar word is not enough. Ask which grammar rule and which early error rule apply at that exact spot.

The table below is the same one from earlier. It compares the three ways code can fail.

When each kind of failure happens
What went wrongWhyWhat you see
The code does not fit the grammar.The tokens cannot be joined into a script or module, like add(3 with no closing bracket.A SyntaxError. No line of that file runs.
An early error.The code fits the grammar, but an extra rule forbids it, like two let price lines.A SyntaxError. No line of that file runs.
A runtime error.The script starts, then one line fails while running, like calling missingPrice().Lines before it have already run, so their prints show.

Practice exercises

For each one, first guess what prints. Then name the rule that explains it. Each starting program is only a few lines long.

Use Edit & run to try the programs that work. For a program that fails on purpose, read it and explain why. Don't try to fix it inside the same script.

Exercise 1 · Warm-upRead a value in brackets

A receipt stores a price in round brackets. Guess what prints. Then say why these are grouping brackets and not arrow parameters.

Starter codePop out in the code editor (opens in a new tab)JavaScript
const price = (3);
console.log(price);

Answer, then press Check. Spacing and letter case don’t matter.

    Exercise 2 · Warm-upTell when a call fails

    A checkout script prints a word, then calls a function that does not exist. Is this an early error or a runtime error? Also give the first word it prints.

    Starter codePop out in the code editor (opens in a new tab)JavaScript
    console.log("before");
    try {
      missingPrice();
    } catch (error) {
      console.log(error.name);
    }

    Answer, then press Check. Spacing and letter case don’t matter.

      Exercise 3 · PracticeDecide what the brackets are

      A price function uses an arrow. Its brackets could be read two ways. Which of the two jobs do they do here? Run the code to check the result too.

      Starter codePop out in the code editor (opens in a new tab)JavaScript
      const add = (price) => price + 2;
      console.log(add(3));

      Answer, then press Check. Spacing and letter case don’t matter.

        Exercise 4 · PracticeFind the declared name

        A cart has a tea property. Which new variable name does the destructuring create? Don't answer with the property name.

        Starter codePop out in the code editor (opens in a new tab)JavaScript
        const { tea: price } = { tea: 3 };
        console.log(price);

        Answer, then press Check. Spacing and letter case don’t matter.

          Exercise 5 · ChallengeSpot a function that cannot start

          The developer expects the print above the function to run. Can this script start? Name the two checks that decide it.

          Starter codePop out in the code editor (opens in a new tab)JavaScript
          console.log("before");
          function total(price = 3) {
            "use strict";
            return price + 2;
          }

          Answer, then press Check. Spacing and letter case don’t matter.

            Exercise 6 · ChallengeFix a checkout script

            A real checkout page broke after someone added a second let price. The fixed version declares price once, with destructuring. Guess what it prints, and say why the fixed script can run.

            Starter codePop out in the code editor (opens in a new tab)JavaScript
            const cart = { tea: 3 };
            const { tea: price } = cart;
            console.log(price);

            Answer, then press Check. Spacing and letter case don’t matter.

              Check your understanding

              For each code question, first decide whether the script can start at all. If it can, work out what it prints, in order.

              For questions about the spec, keep three things apart: the shape the grammar allows, the named checks, and what happens while the code runs.

              Syntactic grammar quiz · 8 questionsScore: first tries count
              1. Question 1 of 8In a grammar rule like WhileStatement : while ( Expression ) Statement, what does the single colon tell you?

                Choose an answer to see the explanation.

              2. Question 2 of 8What does this code with a value in round brackets print?

                Read the code, then predictPop out in the code editor (opens in a new tab)JavaScript
                const price = (3);
                console.log(price);

                Choose an answer to see the explanation.

              3. Question 3 of 8How many lines from this script run?

                Read the code, then predictPop out in the code editor (opens in a new tab)JavaScript
                console.log("before");
                let price = 3;
                let price = 4;

                Choose an answer to see the explanation.

              4. Question 4 of 8Which name does BoundNames find in const {tea: price} = cart?

                Choose an answer to see the explanation.

              5. Question 5 of 8Why does JavaScript first read (price) in (price) => price + 2 with a wide rule?

                Choose an answer to see the explanation.

              6. Question 6 of 8What does this function print?

                Read the code, then predictPop out in the code editor (opens in a new tab)JavaScript
                function receipt() {
                  return
                  3;
                }
                console.log(receipt());

                Choose an answer to see the explanation.

              7. Question 7 of 8This script is built correctly. What does it print?

                Read the code, then predictPop out in the code editor (opens in a new tab)JavaScript
                console.log("before");
                try { missingPrice(); } catch (error) { console.log(error.name); }

                Choose an answer to see the explanation.

              8. Question 8 of 8Can a function with the parameter price = 3 have a "use strict" line in its body?

                Choose an answer to see the explanation.

              Key takeaways

              When you read a piece of code against the spec, go in this order:

              1. Find the grammar rule for it.
              2. Check its settings, like [In], and its marks, like opt or [no LineTerminator here].
              3. Read the early error rules for it.
              4. Only then work out what the code prints or throws when it runs.
              • Grammar rules say how tokens join into bigger pieces. Settings like [Yield] switch parts of a rule on or off, depending on where the code sits.
              • Optional parts (opt), lookahead rules, and places where a line break is not allowed all change which code is accepted.
              • Round brackets can group a value or hold arrow parameters. JavaScript reads them with a wide rule first. What comes after them decides their job, and then they must fit the stricter rule for that job.
              • An early error rejects the whole script or module before its first line runs.
              • The named checks (BoundNames, VarDeclaredNames, LexicallyDeclaredNames, IsSimpleParameterList, and ContainsUseStrict) only read the written code. They never look at values while code runs.
              • A runtime error like ReferenceError can come after an earlier print. An early SyntaxError cannot.

              Remember the one-liner.
              The grammar says how code is built. The extra rules say whether that code is allowed to run.

              Coming next: Evaluation order. It follows the steps an allowed expression takes, from left to right. To see how engines read code, try Parsing and ASTs.

              CompleteFrontend Clear concepts. Working examples.