In JavaScript, a statement is a single instruction that the browser can execute. Think of it as a sentence in a programming language. Statements tell JavaScript what to do, such as declare a variable, perform a calculation, or show a message.
Each statement typically ends with a semicolon (;), though in many cases JavaScript can handle missing semicolons automatically.
1️⃣ Types of JavaScript Statements
Variable Declaration Statements
Used to declare variables that store data.
let name = "Alice"; // Declare a variable using let const pi = 3.1416; // Declare a constant var city = "Paris"; // Declare a variable using var (older)
let → modern, block-scopedconst → constant, cannot be reassignedvar → older, function-scopedExpression Statements
Expression statements compute a value. Most assignments or operations are expressions.
let x = 5; // Assignment expression x = x + 2; // Updates the value of x console.log(x); // Output: 7
Conditional Statements
Used to make decisions based on conditions.
let age = 18;
if(age >= 18) {
console.log("You are an adult");
} else {
console.log("You are a minor");
}
if → checks a conditionelse → executes if condition is falseLoop Statements
Used to repeat a block of code multiple times.
for(let i = 1; i <= 5; i++) {
console.log("Number " + i);
}
for loop repeats code 5 timeswhile, do...whileFunction Statements
Functions are reusable blocks of code.
function greet(name) {
console.log("Hello, " + name + "!");
}
greet("Alice"); // Calls the function
Break and Continue Statements
Used inside loops to control flow.
for(let i = 1; i <= 5; i++) {
if(i === 3) break; // Stops the loop when i is 3
console.log(i);
}
for(let i = 1; i <= 5; i++) {
if(i === 3) continue; // Skips the iteration when i is 3
console.log(i);
}
break → exits the loop completelycontinue → skips current iterationExplanation:
let)age<!DOCTYPE html>
<html>
<head>
<title>JavaScript Statements Example</title>
<style>
body { font-family: Arial; padding: 20px; }
button { padding: 10px 20px; margin: 5px; cursor: pointer; }
p { font-size: 18px; color: darkgreen; }
</style>
</head>
<body>
<h1>JavaScript Statements Demo</h1>
<p id="demo">Click the button to see statements in action</p>
<button onclick="runStatements()">Run Statements</button>
<script>
function runStatements() {
// Variable Declaration Statement
let userName = "Alice";
let age = 25;
// Expression Statement
age += 1; // Increment age
// Conditional Statement
let message;
if(age >= 18) {
message = userName + " is an adult.";
} else {
message = userName + " is a minor.";
}
// Loop Statement
let numbers = "";
for(let i = 1; i <= 3; i++) {
numbers += i + " ";
}
// Function Statement (inner function)
function greeting() {
return "Hello, " + userName + "!";
}
// Display results
document.getElementById("demo").innerHTML =
greeting() + "<br>" +
"Age next year: " + age + "<br>" +
message + "<br>" +
"Numbers: " + numbers;
}
</script>
</body>
</html>