JavaScript Statements
In JavaScript, a statement is a unit of code that performs an action. Statements are executed sequentially and are the building blocks of JavaScript programs. Each statement is typically terminated with a semicolon (`;`).
1. Declaration Statements
Declaration statements are used to declare variables or constants. They define variables or constants that can be used throughout your code.
<script>
// Variable declaration
var name = 'John';
// Constant declaration
const age = 30;
</script>
In the example above, `var name = 'John';` declares a variable `name` and assigns it the value 'John'. Similarly, `const age = 30;` declares a constant `age` with the value 30.
2. Expression Statements
Expression statements are used to perform operations and produce a result. They can include arithmetic operations, function calls, and more.
<script>
// Expression statement
var result = 5 + 10;
console.log(result); // Output: 15
</script>
In the example above, `var result = 5 + 10;` is an expression statement that calculates the sum of 5 and 10, and `console.log(result);` outputs the result to the console.
3. Control Flow Statements
Control flow statements determine the order in which other statements are executed. Examples include conditional statements and loops.
<script>
// Conditional statement
if (true) {
console.log('Condition is true');
} else {
console.log('Condition is false');
}
// Loop statement
for (var i = 0; i < 5; i++) {
console.log(i);
}
</script>
In the example above, the `if` statement checks a condition and executes code based on whether the condition is true or false. The `for` loop iterates from 0 to 4 and logs each value to the console.