JavaScript Statements
Why should you care about JavaScript Statements?
Statements are the building blocks of every JavaScript program. Once you understand how they work, reading and writing real code becomes much clearer and less error-prone.
A JavaScript program consists of instructions that tell the computer what to do. These instructions are called statements. You have already written statements in previous lessons:
let name = "Sam";
console.log(name);
name = "Alex";
console.log(name); // AlexIn this lesson, you will learn what statements are, how they differ from expressions, and how JavaScript organizes them.
A statement is an instruction that JavaScript executes. It can declare a variable, assign a value, call a function, make a decision, repeat an action, or return a value.
let age = 30;
console.log(age);
age = age + 1;
if (age > 18) {
console.log("Adult");
}JavaScript generally executes statements from top to bottom. Some statements, such as conditions, loops, and function calls, can change the order in which code runs. Review related ideas in Variables, Functions, Loops and Switch, and Conditional Statements.
Run a statement step by step.
You have already seen several types of JavaScript statements:
- Variable declaration:
const age = 30; - Assignment:
age = 31; - Function call:
console.log(age); - Conditional statement:
if (age >= 18) { ... } - Loop:
for (let i = 0; i < 3; i++) { ... } - Return statement:
return total;
You do not need to memorize every type. Just remember that a statement is an instruction JavaScript can execute.
An expression is a piece of code that produces a value.
2 + 2produces4.ageproduces the value stored in the variable.user.nameproduces the value of thenameproperty.getTotal()produces the value returned by the function.trueand"Hello"are also expressions because they are values.
const total = 2 + 2;
console.log(total); // 4
// 2 + 2 is the expression.
// The complete line is a declaration statement.In this example, 2 + 2 is an expression because it produces a value. The complete line const total = 2 + 2; is a statement that declares a variable.
See how expressions and statements work together.
| Code | Concept | Why |
|---|---|---|
2 + 2 | Expression | Produces 4. |
user.name | Expression | Produces a value. |
getTotal() | Expression | Produces a result. |
const total = 2 + 2; | Statement | Declares a variable and contains an expression. |
console.log(total); | Expression statement | Uses an expression as a complete instruction. |
if (...) { ... } | Statement | Controls execution. |
return total; | Return statement | Ends function execution and returns a value. |
Remember: An expression produces a value. A statement is an instruction JavaScript can execute. A statement can contain one or more expressions.
An expression statement is an expression used as a complete instruction. Function calls, assignments, and property updates are common examples.
let count = 0;
const user = { name: "Alex" };
console.log("Hello");
count = count + 1;
user.name = "Sam";
console.log(count, user.name); // 1 SamIn this example, function calls, assignments, and property updates are used as statements. For example, console.log("Hello"); is an expression statement because it uses a function call as a complete instruction.
Many JavaScript statements are written on a single line, especially variable declarations, assignments, and function calls.
let score = 100;
console.log(score);
score = score - 10;
console.log(score); // 90Each line contains a complete statement. JavaScript also allows multiple statements on one line when they are separated by semicolons, but writing them on separate lines makes code easier to read.
// Technically valid, but avoid this style
let x = 5; let y = 10; console.log(x + y);A code block is a group of statements enclosed in curly braces: { ... }. The braces group statements together so they can be controlled as one unit.
const temperature = 30;
if (temperature > 25) {
const message = "It is hot outside.";
console.log(message);
console.log("Stay hydrated!");
}
function greet(name) {
const greeting = "Hello, " + name + "!";
console.log(greeting);
}
greet("Sam");Both the if body and the function body are blocks. Blocks commonly appear in if/else, loops, functions, and try/catch. Curly braces matter because they show exactly which statements belong together.
Beginner tip: Use curly braces consistently with conditions and loops. They make it clear which statements belong together and help prevent mistakes.
A semicolon (;) is commonly used to mark the end of a JavaScript statement.
const city = "Paris";
console.log(city);JavaScript can automatically insert semicolons in certain situations. This feature is called Automatic Semicolon Insertion (ASI). Although semicolons are optional in many cases, writing them explicitly and consistently is a good habit.
Automatic Semicolon Insertion (ASI) is a JavaScript feature that automatically inserts semicolons in certain situations when required by the language syntax. For example:
let country = "France"
console.log(country)This code works without explicitly written semicolons. However, ASI does not insert a semicolon after every newline. It follows specific JavaScript syntax rules.
JavaScript treats the line break after return as the end of the statement. As a result, the function returns undefined instead of the object.
function getConfig() {
return
{
theme: "dark"
};
}
console.log(getConfig()); // undefinedKeep the returned value on the same line as return:
function getConfig() {
return {
theme: "dark"
};
}
console.log(getConfig());Remember: Do not place a line break immediately after return when you want to return a value.
Whitespace includes spaces, tabs, and newlines. JavaScript generally ignores extra whitespace between tokens, but proper spacing and indentation make code easier to read.
const total = 10 + 5;
const compactTotal=10+5;
if (total > 10) {
console.log("Greater than 10");
}Whitespace can be meaningful inside strings and in certain parts of JavaScript syntax. Use consistent spacing and indentation to make your code easier to understand and maintain.
- Thinking every line is a statement:
2 + 2is an expression, not a statement by itself. - Thinking every newline creates a semicolon: ASI follows grammar, not every line break.
- Putting
returnon its own line: this can returnundefined. - Putting multiple statements on one line: valid with semicolons, but harder to read.
- Using poor indentation: the engine may run the code, but humans struggle to see its structure.
- Confusing a block with a statement:
{ ... }groups statements and is used by many statements.
- Is
2 + 2an expression or a statement? - Is
const total = 2 + 2;a statement or expression? - What does
console.log(2 + 3);do? - Identify the block in
if (age > 18) { console.log("Adult"); console.log("Allowed"); }. - What does the
returnnewline example return? - Which is easier to read:
const x = 5; const y = 10; console.log(x + y);or three separate lines? Explain why.
Answers: 1. Expression. 2. Statement containing an expression. 3. It calls console.log with the value 5. 4. The statements between { and }. 5. undefined, because ASI ends return. 6. Three separate lines are easier to scan and maintain.
- Statement: An instruction JavaScript can execute.
- Expression: Code that produces a value.
- Expression statement: An expression used as a complete instruction.
- Code block: A group of statements enclosed in
{ }. - Semicolon: Commonly marks the end of a statement.
- ASI: JavaScript can insert semicolons automatically in certain situations.
- Return and newline: A line break after
returncan cause an unexpected result. - Whitespace: Usually ignored between tokens, but important for readable code.
Now that you understand how JavaScript statements work, let's learn how to display messages and interact with users using JavaScript popup boxes.
- What is a statement in programming?
- Calculate and print a discounted price with one statement.
- Calculate and print a price with tax using separate statements.
- What is a code block?
- What is a statement in JavaScript?
- How does an `if...else` statement choose which block to run?
- What causes fall-through between `switch` cases?
- How do `break` and `continue` affect a loop?
- Does a `finally` block run when control leaves a `try` block?
- Why use a block statement after a conditional?
- How does `switch` compare a case expression with its value?
- What happens if both `try` and `finally` contain a `return`?
- When can a labeled `break` be useful?
- When is a `do...while` loop different from a `while` loop?
- Why can mutating an array while iterating it be error-prone?