A JavaScript program consists of a series of "instructions" that the web browser "executes".
These instructions are known as statements.
JavaScript statements consist of:
- Values
- Operators
- Expressions
- Keywords
- Comments
Example: Instruct the browser to display "WebmasterMaze." inside an HTML element with the id="statement".
document.getElementById("statement").innerHTML = "WebmasterMaze";
- Most JavaScript programs consist of multiple statements.
- These statements are executed sequentially, in the exact order they are written.
- Semicolons are used to separate JavaScript statements.
More Examples:
<p id="let"></p>
<script>
let a, b, c; // Statement 1
a = 5; // Statement 2
b = 6; // Statement 3
c = a + b; // Statement 4
document.getElementById("let").innerHTML = "The value of c is " + c + ". ";
</script>
<!-- Output: The value of c is 11. -->
Multiple statements can be written on a single line if separated by semicolons.
a = 5; b = 6; c = a + b;
On the web, you may come across examples that omit semicolons. While it’s not strictly necessary to end statements with a semicolon, it is strongly recommended for better code clarity and reliability.
A good practice is to include spaces around operators (such as =, +, -, *, /) for better readability.
let c = a + b;
JavaScript Keywords
JavaScript statements typically begin with a keyword that specifies the action to be performed.
Below is a list of some of the commonly used keywords.
var
- Declares a variable.let
- Declares a block-scoped variable.const
- Declares a block-scoped constant.if
- Defines a block of statements to be executed based on a condition.switch
- Defines a block of statements to be executed in different cases.for
- Defines a loop that repeats a block of statements.function
- Declares a function.return
- Exits a function and optionally returns a value.try
- Implements error handling within a block of statements.