JavaScript Statements

A JavaScript program is built from statements, the individual instructions that the browser executes one after another.

What Is a Statement?

A statement is a single, complete instruction that tells the computer to do something, such as declaring a variable, performing a calculation, or calling a function. A JavaScript program is essentially a list of these statements, and the engine runs them in the same order they are written, from top to bottom.

Example

<!DOCTYPE html>
<html>
<body>

<h2>What Is a Statement?</h2>

<script>
let a = 5;        // statement 1
let b = 6;        // statement 2
let c = a + b;    // statement 3
console.log(c);   // statement 4
</script>

</body>
</html>

Semicolons and Whitespace

Statements are separated by semicolons. While JavaScript can often insert them automatically, relying on that behavior can lead to surprising bugs, so it is safer to end each statement with a semicolon yourself. Blank lines and indentation have no effect on how code runs, but they make programs far easier for humans to read.

  • Place a semicolon at the end of each statement to mark where it finishes.
  • You may write several short statements on one line if each ends with a semicolon.
  • Extra spaces and line breaks between tokens are ignored by the engine.
  • Consistent indentation shows how code is grouped and nested.

Keywords and Code Blocks

Many statements begin with a keyword that identifies the action to perform, such as if for a decision or for to start a loop. Related statements are often grouped together inside a code block, marked by a pair of curly braces. Blocks let you treat many statements as a single unit, which is essential for conditions, loops, and functions.

Example

<!DOCTYPE html>
<html>
<body>

<h2>Keywords and Code Blocks</h2>

<script>
// A code block groups statements together
if (hour < 18) {
  greeting = "Good day";
  console.log(greeting);
} else {
  greeting = "Good evening";
  console.log(greeting);
}
</script>

</body>
</html>
Note: Think of curly braces as a container: everything between the opening and closing brace belongs to the same block and runs together as one group.
KeywordStatement typeWhat it does
let / constDeclarationCreates a variable
if / elseConditionalRuns code based on a test
for / whileLoopRepeats code multiple times
returnFunction controlSends a value back from a function

Exercise: JavaScript Statements

What is a JavaScript statement?