JavaScript ยท Chapter 4 of 55

JavaScript Statements

A JavaScript program is a list of statements executed by the browser in the order they're written. Each statement typically performs one instruction, like assigning a value or calling a function.

Statements are usually separated by semicolons, though JavaScript can often infer them automatically via a mechanism called Automatic Semicolon Insertion (ASI).

Statement basics

A statement can be a variable declaration, an assignment, a function call, or a control structure like if or for. Multiple statements form a script.

Semicolons

While ASI allows omitting semicolons in many cases, relying on it can cause subtle bugs. Best practice is to always end statements with a semicolon.

Example 1 (javascript)
let x = 5;
let y = 6;
let z = x + y;
console.log(z);
Output
11

Three statements execute in sequence, then the result is logged.

Example 2 (javascript)
{
  let a = 1;
  let b = 2;
  console.log(a + b);
}
Output
3

Curly braces group statements into a block.

Key points

  • Statements execute top to bottom, in order.
  • Semicolons separate statements (recommended even though optional).
  • Curly braces `{}` group statements into blocks.
  • Whitespace and line breaks are mostly ignored by the interpreter.
๐Ÿ’ก Note: Always terminate statements with semicolons to avoid rare ASI bugs.

๐Ÿ“ Quick Quiz

1. What character typically ends a JS statement?

2. What does ASI stand for?

3. What groups statements into a block?