A statement in JavaScript is a single instruction or command that performs an action.
1. Types of Statements
Expression Statements
An expression that produces a value and is followed by a semicolon (;
). For example:
let x = 5; // Assigning a value to a variable x++; // Incrementing the value of x
Declaration Statements
Used to declare variables, functions, or objects. They define entities but don’t necessarily produce a value.
let name; // Declaring a variable function greet() {} // Declaring a function
Control Flow Statements
These statements control the flow of execution based on conditions, loops, or jumps.
- Conditional Statements:
if
statement:if (x > 10) { console.log("x is greater than 10"); }
if...else
statement:if (x > 10) { console.log("x is greater than 10"); } else { console.log("x is 10 or less"); }
- Switch Statement: Used to select one of many code blocks to be executed.
switch (day) { case 1: console.log("Monday"); break; case 2: console.log("Tuesday"); break; default: console.log("Other day"); }
- Loops:
for
loop:for (let i = 0; i < 5; i++) { console.log(i); }
while
loop:let i = 0; while (i < 5) { console.log(i); i++; }
Jump Statements
- Break Statement: Exits from a loop or switch statement.
for (let i = 0; i < 5; i++) { if (i === 3) { break; } console.log(i); }
- Continue Statement: Skips the current iteration of a loop and moves to the next one.
for (let i = 0; i < 5; i++) { if (i === 3) { continue; } console.log(i); }
Return Statement
Used to exit a function and optionally return a value.
function add(a, b) { return a + b; } console.log(add(3, 4)); // Output: 7
2. Semicolon (;
)
Statements are typically terminated with a semicolon, although JavaScript has automatic semicolon insertion (ASI), meaning it will often add semicolons where they are missing. However, it’s good practice to explicitly include them.
Conclusion
Statements form the core building blocks of JavaScript. Understanding different types of statements—like expressions, control flows, loops, and jumps—will help you write effective JavaScript code to handle various tasks and logic.