JavaScript Statements
2 April 2025 | Category: JavaScript
What Are JavaScript Statements?
A JavaScript statement is an instruction that the browser executes to perform an action. JavaScript code consists of a series of statements that are executed one by one, in order.
🔹 Example of a simple statement:
let x = 10; // This is a statement that declares a variable
console.log(x); // This statement prints x to the console
Types of JavaScript Statements
JavaScript has different types of statements, including:
1️⃣ Declaration Statements (e.g., let
, const
, var
)
2️⃣ Assignment Statements (e.g., x = 5;
)
3️⃣ Control Flow Statements (e.g., if
, switch
)
4️⃣ Looping Statements (e.g., for
, while
)
5️⃣ Function Statements (function
)
1️⃣ Declaration Statements (Variables & Constants)
These statements declare variables that store values.
🔹 Example:
let name = "John"; // Declares a variable
const PI = 3.14; // Declares a constant
2️⃣ Assignment Statements
Assignment statements assign values to variables.
🔹 Example:
let x; // Declaration
x = 10; // Assignment
3️⃣ Control Flow Statements (Conditional Statements)
These statements control decision-making in JavaScript.
🔹 If-Else Statement Example:
let age = 18;
if (age >= 18) {
console.log("You are an adult.");
} else {
console.log("You are a minor.");
}
🔹 Switch Statement Example:
let fruit = "apple";
switch (fruit) {
case "banana":
console.log("Banana selected.");
break;
case "apple":
console.log("Apple selected.");
break;
default:
console.log("Invalid choice.");
}
4️⃣ Looping Statements (Loops)
Loops repeat a block of code multiple times.
🔹 For Loop Example:
for (let i = 1; i <= 5; i++) {
console.log("Count: " + i);
}
🔹 While Loop Example:
let num = 1;
while (num <= 5) {
console.log("Number: " + num);
num++;
}
5️⃣ Function Statements
Functions group reusable code into a block.
🔹 Example:
function greet(name) {
console.log("Hello, " + name + "!");
}
greet("Alice"); // Output: Hello, Alice!
🚀 JavaScript Statement Rules
✅ Each statement ends with a semicolon (;
) (optional but recommended).
✅ JavaScript ignores extra spaces and new lines.
✅ Statements execute in order unless controlled by conditions or loops.
🔍 Summary of JavaScript Statements
Statement Type | Example | Purpose |
---|---|---|
Declaration | let x = 10; | Declares variables/constants |
Assignment | x = 5; | Assigns values to variables |
Conditional | if (x > 10) {} | Controls execution flow |
Looping | for (let i = 0; i < 5; i++) {} | Repeats code |
Function | function greet() {} | Creates reusable code |
🎯 Conclusion
- JavaScript statements are the instructions that tell the browser what to do.
- Statements can be simple (variable assignment) or complex (loops, functions).
- Using proper syntax and structure helps in writing efficient JavaScript code.