JavaScript Statements and Blocks – Code Structure
In JavaScript, statements are the building blocks of code that perform actions, such as assignments or function calls. Blocks are groups of statements enclosed in curly braces {}.
1. JavaScript Statements
A statement is an instruction that performs an action. For example, assignments, loops, conditionals, and function calls are all types of statements.
Types of Statements:
- Expression Statement: Contains an expression that is evaluated and performs an action.
let x = 10; // This is an expression statement.
- Declaration Statement: Used to declare variables, functions, or classes.
let name; // Variable declaration statement. function greet() {} // Function declaration statement. - Control Flow Statements: Includes conditionals (if, else), loops (for, while), and switch.
if (x > 5) { console.log("x is greater than 5"); } - Return Statement: Exits a function and optionally returns a value.
return 42;
- Break and Continue Statements: Used to control loop execution.
break; // Exits the loop. continue; // Skips to the next iteration.
Example of Multiple Statements:
let a = 5; // Declaration statement a += 10; // Expression statement console.log(a); // Function call statement
2. JavaScript Blocks
A block is a group of statements enclosed in curly braces {}. Blocks are often used in control structures such as loops, conditionals, and functions to group multiple statements together.
Syntax of a Block:
{
statement1;
statement2;
...
}
Example of a Block:
if (x > 10) {
let result = x * 2; // This is inside the block.
console.log(result); // This is inside the block.
}
- In the example above, the block
{}groups the statements together, and the block will execute only if the conditionx > 10is true.
Blocks in Functions:
A function is a block of code that performs a task. You can have multiple statements inside the block of a function.
function calculate(a, b) {
let sum = a + b;
let difference = a - b;
return sum * difference;
}
let result = calculate(10, 5); // Calls the function
console.log(result); // 75
3. Block Scope vs Function Scope
- Block Scope: Variables declared within a block (using
letorconst) are only accessible inside that block.if (true) { let a = 10; // a is scoped to the block } console.log(a); // Error: a is not defined - Function Scope: Variables declared within a function are only accessible inside that function.
function myFunction() { let x = 20; } console.log(x); // Error: x is not defined
4. Important Notes
- A semicolon
;is typically used to terminate a statement in JavaScript. - Blocks are used to group multiple statements and can be used in control structures, functions, and loops.
Conclusion:
- Statements perform actions like assignments, conditionals, loops, and function calls.
- Blocks group multiple statements together and are used with control structures like
if,for, andwhile. - Understanding block scope and function scope helps you manage variable visibility in JavaScript.