Thuta Learning
JavaScript
BasicProgrammingBeginner

JS Syntax

JavaScriptLesson 320 min

What you'll walk away with

  • Tell statements (instructions) apart from expressions (code that produces a value)
  • Use blocks, comments and identifier naming rules correctly
  • Find bugs caused by JavaScript being case-sensitive
  • Avoid the return trap of automatic semicolon insertion

Explain it simply

Explain it simply

Syntax is the grammar of a programming language: the rules for arranging words and symbols so the engine can understand them. In English you can make a small spelling mistake and people still understand you.

JavaScript is stricter. A missing quote or } stops the whole file, and a name with different capital letters means something else entirely. The good news is that a handful of rules (statements, expressions, blocks, comments and case) cover almost everything you will write.

Problem → Why → Solution

The problem: one wrong character stops the program

The code below has two mistakes. username is written with a lowercase n, so it is not the same name as userName, and the closing } of the if block is missing. Surprisingly, running the file shows only a SyntaxError, not the ReferenceError: not even the first two lines run.

welcome.js
let userName = "Mya";
console.log(username);   // wrong case: ReferenceError... later

if (userName) {
  console.log("Welcome back");
// the closing } is missing

// $ node welcome.js
// SyntaxError: Unexpected end of input

Why do you only see the SyntaxError?

The engine reads a file in two phases. First it parses the whole file into a structure; a grammar error found here (a SyntaxError) stops everything before a single line runs. Then it executes statement by statement, and errors such as a misspelt name (a ReferenceError) only appear when that line is reached. Knowing which phase an error comes from tells you where to look.

Core concept: statements that contain expressions

A program is a list of statements. A statement is one instruction: declare a variable, assign a value, call a function, make a decision. The engine runs statements in order from top to bottom. A semicolon (;) ends a statement, and by convention each line holds one statement.

An expression is any piece of code that produces a value: 5, x + y, "Hi " + name, x > 3. Expressions live inside statements. In let z = x + y; the expression x + y is evaluated first, and then the statement stores the result in z. A handy test: if it could go inside console.log(...), it is an expression.

Curly braces { } group statements into a block, which if statements, loops and functions use. The engine ignores spaces and indentation, but humans need them. Identifiers (names) are case-sensitive: total, Total and TOTAL are three different names, and keywords are lowercase (let, not Let). Names may contain letters, digits, _ and $, but cannot start with a digit, and reserved words such as let, class or return cannot be names. JavaScript convention is camelCase, as in firstName.

Comments come in two forms: // ignores the rest of the line, and /* ... */ can span several lines. Use comments to explain why the code does something rather than what it does, and to switch a line off temporarily while debugging. Strings can use double quotes, single quotes or backticks. Pick one quote style for a project, and use the other kind when the text itself contains a quote, as in "It's fine".

PieceExampleJob
Statementlet z = x + y;Performs one instruction
Expressionx + yProduces a value
Block{ ... }Groups statements
Comment// note /* note */Ignored by the engine
Mental model: parse first, then run
  1. The engine parses the whole file
  2. A grammar error means nothing runs
  3. Statements run from top to bottom
  4. Expressions are evaluated inside them

SyntaxError comes from parsing; ReferenceError and TypeError come from running.

General pattern

javascript
// a comment: ignored by the engine
let name = expression;       // statement containing an expression
name = name + otherValue;    // reassignment statement

{                            // a block groups statements
  statementOne;
  statementTwo;
}

The expression on the right of = is evaluated first and stored in the name on the left. A bare block is rare; you mostly see blocks as part of if, for and function.

Example: four statements

This program has four statements and three comments. Find the expression inside each statement, then change x to 7 and predict the new output.

javascript
// Declaring variables
let x = 5;
let y = 10;

// An expression that calculates a value
let z = x + y;

// Output the result to the console
console.log("The value of z is: " + z);

Code breakdown

  1. Line 1// Declaring variables

    A line starting with // is a comment. The engine skips it entirely; it is a note for human readers.

  2. Line 2let x = 5;

    Declares a variable named x with the let keyword and stores the expression 5 in it. The semicolon marks the end of the statement.

  3. Line 6let z = x + y;

    x + y is the expression. The engine looks up x (5) and y (10), computes 15 and stores it in z. Writing X + y here would throw ReferenceError: X is not defined.

  4. Line 9console.log("The value of z is: " + z);

    A function-call statement. The expression in the parentheses joins a string and a number with +, so 15 is turned into text and the result is "The value of z is: 15".

You should see
The value of z is: 15

Semicolons and automatic semicolon insertion

When you leave a semicolon out, JavaScript inserts one automatically at most line breaks (automatic semicolon insertion, or ASI). That is why code without semicolons usually works. There is one classic trap: a line break straight after return makes the engine read return; and return undefined, so the object on the next line is never reached.

asi-trap.js
function getConfigBroken() {
  return
    { debug: true };
}

function getConfigFixed() {
  return { debug: true };
}

console.log(getConfigBroken()); // undefined
console.log(getConfigFixed());  // { debug: true }

Whichever style you choose, with or without semicolons, use it consistently across a project, and always start the return value on the same line as return.

In real projects

Where this shows up in real projects

Teams use a formatter such as Prettier and a linter such as ESLint so nobody argues about semicolons, quote style or indentation. Saving a file reformats it into one consistent shape, and the linter warns about unused variables and misspelt names before the code runs. Code review can then focus on logic instead of syntax style.

JavaScript shipped to production is usually minified: spaces, comments and line breaks are stripped and names are shortened, which shows how little the engine cares about them. When an error happens, a source map points the minified code back to the original file and line number. Reading a syntax error quickly is a daily skill too: the message names the file, line and column, and usually adds a hint such as Unexpected token or missing ) after argument list.

Common mistakes

Common mistakes

1. Getting capital letters wrong

Console.log("hi") throws ReferenceError: Console is not defined, and document.getElementByID(...) throws TypeError: ... is not a function because the real name is getElementById. Let the editor's autocomplete type names for you.

2. Leaving a quote, bracket or brace open

One unclosed ", ( or { turns the whole file into a SyntaxError. The message may point at the end of the file even though the real mistake is higher up, so use the editor's bracket matching and the indentation to find the pair that does not close.

3. Naming a variable with a reserved word or a leading digit

let class = "A"; and let 2ndPlace = "Ko Ko"; are both SyntaxErrors. Choose descriptive names such as selectedClass and secondPlace instead.

Best practices

Best practices

  • Write one statement per line and end each with a semicolon (or rely on ASI consistently, with a linter watching).
  • Indent every block by the same amount (2 spaces is common in JavaScript) so the shape of the code matches its logic.
  • Use full words in camelCase for names: totalPrice beats tp.
  • Let a formatter fix the layout on save instead of aligning code by hand.

Mini challenge

Mini challenge: a shopping receipt

Write a program that prints a short receipt for one item, with one statement per line.

  • Declare itemName ("Notebook"), price (2.5) and quantity (4) as variables
  • subtotal is price times quantity, tax is 10% of subtotal, total is subtotal plus tax
  • Print three lines: the item line, the subtotal line and the total line
  • End every statement with a semicolon
receipt.js
// TODO: declare itemName, price and quantity (one statement per line)

// TODO: subtotal = price times quantity

// TODO: tax = 10% of subtotal, total = subtotal plus tax

// TODO: print "Notebook x 4", "Subtotal: ..." and "Total: ..."

Expected: Three lines are printed: Notebook x 4 Subtotal: 10 Total: 11

Show hint

10% is a multiplication by 0.1. Joining a string and a number with + gives text: "Total: " + total.

Show solution
receipt.js
let itemName = "Notebook";
let price = 2.5;
let quantity = 4;

let subtotal = price * quantity;
let tax = subtotal * 0.1;
let total = subtotal + tax;

console.log(itemName + " x " + quantity);
console.log("Subtotal: " + subtotal);
console.log("Total: " + total);

Quick quiz 1 / 3

Which of these is an expression (it produces a value) rather than a statement?

Quick quiz 2 / 3

Given function f() { return 42; }, what does console.log(f()); print?

Quick quiz 3 / 3

What happens when you run let Score = 10; console.log(score);?

What to remember

  • A program is a list of statements, and statements contain expressions that produce values.
  • { } forms a block, // and /* */ are comments, and spacing exists for human readers.
  • JavaScript is case-sensitive: userName and username are two different names.
  • A SyntaxError stops the whole file; keep a return value on the same line as return.

MDN — JavaScript Guide — MDN Web Docs

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.