JavaScript Statements
In JavaScript, statements are instructions that the browser executes. A program is made up of a
sequence of these statements.
Types of JavaScript Statements
1. Declaration Statements
Used to declare variables or constants.
var, let, const
let x = 10; // Declares a variable
const PI = 3.14; // Declares a constant
2. Expression Statements
Evaluate an expression and assign a value.
let sum = 5 + 10; // Sum is assigned 15
3. Conditional Statements
Used for decision-making.
if
Executes a block of code if the condition is true.
if (x > 5) {
[Link]("x is greater than 5");
}
if-else
Adds an alternative block if the condition is false.
if (x > 5) {
[Link]("x is greater than 5");
} else {
[Link]("x is 5 or less");
}
else if
Used for multiple conditions.
if (x > 10) {
[Link]("x is greater than 10");
} else if (x > 5) {
[Link]("x is greater than 5 but less than or equal to 10");
} else {
[Link]("x is 5 or less");
}
4. Looping Statements
Execute a block of code multiple times.
for loop
for (let i = 0; i < 5; i++) {
[Link](i);
}
while loop
let i = 0;
while (i < 5) {
[Link](i);
i++;
}
do-while loop
Executes at least once.
let i = 0;
do {
[Link](i);
i++;
} while (i < 5);
5. Switch Statement
Executes one block of code out of multiple options.
let day = 2;
switch (day) {
case 1:
[Link]("Monday");
break;
case 2:
[Link]("Tuesday");
break;
default:
[Link]("Other day");
}
6. Break and Continue Statements
break: Exits the loop immediately.
for (let i = 0; i < 5; i++) {
if (i === 3) break;
[Link](i); // Prints 0, 1, 2
}
continue: Skips the current iteration and continues with the next.
for (let i = 0; i < 5; i++) {
if (i === 3) continue;
[Link](i); // Prints 0, 1, 2, 4
}
7. Function Statements
Define reusable blocks of code.
function greet(name) {
return `Hello, ${name}!`;
}
[Link](greet("Nargis"));
8. Try-Catch-Finally Statement
Handles errors.
try {
let result = x / 0;
} catch (error) {
[Link]("Error occurred: " + [Link]);
} finally {
[Link]("Execution completed");
}
Tips
End statements with a semicolon (;) for clarity, though it's optional.
Use proper indentation for better readability.
Always test code for logic and syntax errors.