Skip to content
Tutorials Center
My learning

Topics

Lesson 3 of 156 ยท Getting Started

Statements, Expressions and Syntax

Learn the grammar of JavaScript - statements vs expressions, semicolons and automatic semicolon insertion pitfalls, case sensitivity, comments and code blocks.

Every language has grammar. In English, a sentence needs a verb and ends with a period. In JavaScript, the rules are stricter, because a computer can't guess what you meant. The set of rules for how code must be written is called syntax.

The good news is that JavaScript's syntax is small and consistent. In this lesson you will learn the two basic building blocks of every program, statements and expressions, along with how semicolons, capital letters, comments and curly braces work. You will also meet two classic traps that catch even experienced developers.

Statements: the instructions

A JavaScript program is a list of statements: instructions that the engine carries out one after another, from top to bottom.

JavaScript
let price = 20;                 // a declaration statement
price = price * 2;              // an assignment
console.log(price);             // a function call
if (price > 30) {               // an if statement...
  console.log("That's pricey!"); // ...with a statement inside
}

Statements are like sentences. Most fit on one line and end with a semicolon. Some, such as if, contain other statements inside curly braces.

Expressions: pieces that produce a value

An expression is any piece of code that produces a value. Expressions are like phrases: they can be small, and they can be combined into bigger ones.

  • 42 and "hello" are expressions (literal values).
  • price is an expression (the value of a variable).
  • price * 2 is an expression built from two smaller ones.
  • price > 30 is an expression whose value is true or false.
  • Math.max(3, 9) is an expression whose value is 9.

A simple test: if you can put it inside console.log(...), it's an expression. Statements can't go there.

JS Expressions produce values

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Many statements are simply an expression followed by a semicolon. console.log(price); is an expression (a function call) used as a statement. You'll see the difference matter later, for example in arrow functions and the ternary operator, which only accept expressions.

Semicolons and automatic semicolon insertion

Semicolons mark the end of a statement. JavaScript has a feature called automatic semicolon insertion (ASI): if you leave a semicolon out at the end of a line, the engine usually adds one for you. So both of these work:

JavaScript
console.log("with a semicolon");
console.log("without one")

Because of ASI, some teams write JavaScript with no semicolons at all, while others always write them. Both styles are valid. In this course we always write semicolons, because then you never have to think about the cases where ASI does something you didn't expect. And there are such cases.

Pitfall 1: a line break after return

ASI inserts a semicolon right after return if the value starts on the next line. The function below looks like it returns an object, but it actually returns nothing at all:

JS The return line-break trap

Press Run (or Ctrl + Enter) to see the console output here.

No output.

JavaScript reads the first function as return; followed by a block it never reaches. The fix is simple: always start the returned value on the same line as return. The same rule applies to break, continue and throw.

Pitfall 2: a line that starts with (, [ or a backtick

The opposite problem happens when a line starts with an opening bracket. ASI only adds a semicolon if the code can't continue, and [ or ( can continue the previous line. So these two lines are glued together:

JS When ASI doesn't insert a semicolon

Press Run (or Ctrl + Enter) to see the console output here.

No output.

You get an error. JavaScript reads the code as "Total: " + total[1, 2, 3].forEach(...): it tries to look up an item in the number 10, gets undefined, and then can't call forEach on that. Add a semicolon at the end of line 2 and the code works. If you write semicolons everywhere, this trap simply never happens.

Let a tool handle it. In real projects, a code formatter such as Prettier adds or removes semicolons consistently for you, and a linter warns about risky line breaks. You will meet these tools in Packages, npm and Build Tools.

JavaScript is case-sensitive

Uppercase and lowercase letters are different characters to JavaScript. score, Score and SCORE are three unrelated names, and built-in names must be written exactly: console.log works, Console.log and console.Log don't.

JS Case matters

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The last line throws a ReferenceError because UserName was never declared. When you see "is not defined" for a name you're sure exists, check its capitalization first. Keywords like let, const, if and function are always lowercase.

Whitespace and line breaks

Outside of strings, JavaScript mostly ignores extra spaces, tabs and blank lines. These two lines do the same thing:

JavaScript
const sum=1+2;
const sum2 = 1 + 2;

Use whitespace to make code readable: spaces around operators, a blank line between groups of related statements, and consistent indentation (this course uses two spaces). Line breaks are the exception, as you saw with ASI: they can change meaning in a few places.

Comments

Comments are notes for humans. The engine skips them completely. JavaScript has two kinds:

JavaScript
// A single-line comment runs to the end of the line.
let speed = 60; // It can also follow code.

/*
  A multi-line comment starts with slash-star
  and ends with star-slash.
*/

/**
 * A comment that starts with two stars is a documentation comment.
 * Editors show it when you hover over the function below.
 * @param {number} km - distance in kilometers
 */
function toMiles(km) {
  return km * 0.621371;
}

Good comments explain why something is done, not what the code does. // add 1 to count adds nothing, but // the API counts pages from 1, not 0 saves the next reader real time. Comments are also useful for temporarily disabling a line while you debug; in most editors, Ctrl + / (Cmd + / on a Mac) toggles a // comment on the current line.

Code blocks

Curly braces { } group several statements into a block. Blocks belong to statements such as if, loops and functions, and everything inside runs together:

JavaScript
if (temperature < 0) {
  console.log("Freezing!");
  console.log("Wear a hat.");
}

Indent the contents of a block one level so the structure is visible at a glance. Notice that a block doesn't need a semicolon after its closing brace. Blocks also limit where variables declared with let and const can be used, which you'll explore in the next lesson.

Identifiers and reserved words

Names you create, such as variable and function names, are called identifiers. They can contain letters, digits, _ and $, but can't start with a digit. A few dozen words are reserved because they are part of the language itself, so you can't use them as names: let, const, if, else, for, while, function, return, class, new, true, false, null and others. The variables lesson covers naming in detail.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which of these is an expression?

    age > 18 produces a value (true or false), so it can be used anywhere a value is expected, for example inside console.log(). The others are statements.
  2. 2. What does this function return? function f() { return (line break) 42; }

    Automatic semicolon insertion turns the line into return;, so the function returns undefined and 42; is never reached.
  3. 3. Which line is most at risk from automatic semicolon insertion when the previous line has no semicolon?

    A line starting with [, ( or a backtick can continue the previous expression, so no semicolon is inserted and the two lines are read as one.
  4. 4. You declared const totalPrice = 9; and then wrote console.log(totalprice);. What happens?

    JavaScript is case-sensitive. totalprice was never declared, so using it throws a ReferenceError saying it is not defined.
  5. 5. Which comment style can span several lines?

    /* ... */ can span many lines. // comments end at the line break. The other two are HTML and Python/shell comments.

Summary

  • A program is a list of statements (instructions) run from top to bottom. Expressions are pieces of code that produce a value.
  • If it can go inside console.log(...), it's an expression.
  • Semicolons end statements. ASI adds missing ones, but watch for line breaks after return and lines starting with (, [ or a backtick. This course always writes semicolons.
  • JavaScript is case-sensitive: name and Name are different.
  • Comments use // for one line and /* */ for several. Write them to explain why.
  • Curly braces group statements into blocks; indent their contents.

Next: Variables: let, const and var โ€” storing and naming values.