Code Blocks & Indentation
Code Blocks & Indentation
A code block is a group of statements wrapped inside curly braces { }. JavaScript uses blocks everywhere — in if statements, loops, functions, and classes.
Blocks tell JavaScript: "run all these statements together as one unit."
Indentation is the spaces you add before each line of code inside a block. JavaScript ignores indentation — but humans depend on it. Good indentation makes your code easy to read and understand.
Blocks are everywhere in JavaScript
Every time you see { and } in JavaScript code, that is a block:
if (x > 0) { ... }— if blockfor (let i = 0; i < 5; i++) { ... }— loop blockfunction greet() { ... }— function blockclass User { ... }— class block
Each block groups its statements together and creates its own scope.
Groups Statements
A block wraps many statements into one unit. Everything inside { } runs together.
Creates Scope
Variables created inside a block with let or const only exist inside that block.
Indentation
Indentation shows which code is inside a block. Use 2 or 4 spaces consistently.
Always Use Braces
Even when a block has just one line, always write the { }. It prevents silent bugs.
What is a Code Block?
What is a Code Block?
A code block is zero or more statements wrapped in curly braces { }. JavaScript treats everything inside the braces as one unit.
You can think of a block like a box. You put instructions inside the box, and JavaScript runs all of them together when the block is reached.
1// A block with if — runs only when condition is true2let temperature = 35;34if (temperature > 30) {5 console.log('It is hot outside.'); // ← inside the block6 console.log('Drink water!'); // ← also inside the block7} // ← block ends here89// A block with for — runs repeatedly10for (let i = 1; i <= 3; i++) {11 console.log('Step', i);12}1314// A block with a function15function greet(name) {16 const message = 'Hello, ' + name + '!';17 console.log(message);18}1920greet('Alice');21greet('Bob');2223// A standalone block (valid but rare)24{25 const note = 'This is a standalone block';26 console.log(note);27}
An empty block is valid
You can write a block with nothing inside it — { }. This is called an empty block. It is valid JavaScript and sometimes useful as a placeholder while you are building code.
function doSomethingLater() {
// TODO: fill this in
}
Where Blocks Are Used
Where Blocks Are Used
Blocks appear in almost every part of JavaScript. Here are all the places you will see them.
1// 1. if / else2const score = 72;3if (score >= 90) {4 console.log('Grade: A');5} else if (score >= 70) {6 console.log('Grade: C'); // this one runs7} else {8 console.log('Grade: F');9}1011// 2. for loop12for (let i = 0; i < 3; i++) {13 console.log('Count:', i);14}1516// 3. while loop17let count = 3;18while (count > 0) {19 console.log('Countdown:', count);20 count--;21}2223// 4. function24function add(a, b) {25 const result = a + b;26 return result;27}28console.log('3 + 4 =', add(3, 4));2930// 5. try / catch31try {32 const data = JSON.parse('{ bad json }');33} catch (error) {34 console.log('Error caught:', error.message);35}3637// 6. class38class Animal {39 constructor(name) {40 this.name = name;41 }42 speak() {43 console.log(this.name + ' makes a sound.');44 }45}46const dog = new Animal('Dog');47dog.speak();
| Context | Syntax | Block ends with ;? |
|---|---|---|
| if / else | if (condition) { } | No |
| for loop | for (...) { } | No |
| while loop | while (condition) { } | No |
| do...while | do { } while (condition); | Yes — the while part |
| function | function name() { } | No |
| class | class Name { } | No |
| try / catch | try { } catch (e) { } | No |
| Standalone block | { } | No |
Block Scope
Block Scope — Variables Live Inside Blocks
Scope means: where can a variable be used?
When you create a variable with let or const inside a block, it only exists inside that block. Once the block ends (the } closes), the variable is gone. You cannot use it outside.
This is called block scope and it is one of the most important concepts in JavaScript.
1// Variables declared OUTSIDE a block — available everywhere below2let globalMessage = 'I am outside';34if (true) {5 // Variables declared INSIDE the block — only available here6 let insideMessage = 'I am inside the if block';7 const insideValue = 42;89 console.log(globalMessage); // ✅ can access outside variable10 console.log(insideMessage); // ✅ can access inside variable11 console.log(insideValue); // ✅ can access inside constant12}1314console.log(globalMessage); // ✅ still works15// console.log(insideMessage); // ❌ ReferenceError — does not exist here16// console.log(insideValue); // ❌ ReferenceError — does not exist here1718// Same with loops19for (let i = 0; i < 3; i++) {20 let loopMessage = 'iteration ' + i;21 console.log(loopMessage);22}23// console.log(loopMessage); // ❌ ReferenceError — gone after the loop24// console.log(i); // ❌ ReferenceError — i is block-scoped too2526console.log('Done!');
var ignores block scope — this is why we avoid it
The old var keyword does NOT respect block scope. A var variable leaks out of any block it is declared in.
if (true) {
var leaked = 'I escape the block!';
}
console.log(leaked); // 'I escape the block!' — no error!
This is a common source of bugs. Always use let or const — they respect block scope. Never use var in modern code.
1// var — leaks out of blocks (bad)2if (true) {3 var oldStyle = 'I leak out!';4}5console.log(oldStyle); // 'I leak out!' — var ignores block scope67// let — stays inside the block (good)8if (true) {9 let newStyle = 'I stay inside.';10 console.log(newStyle); // 'I stay inside.'11}12// console.log(newStyle); // ❌ ReferenceError1314// const — same as let for scope15if (true) {16 const fixed = 'I stay inside too.';17 console.log(fixed); // 'I stay inside too.'18}19// console.log(fixed); // ❌ ReferenceError2021// var also leaks out of for loops!22for (var j = 0; j < 3; j++) {23 // j is var — it leaks24}25console.log('var j after loop:', j); // 3 — leaked out!2627for (let k = 0; k < 3; k++) {28 // k is let — stays inside29}30// console.log(k); // ❌ ReferenceError — k is gone
Indentation
Indentation — Making Code Readable
Indentation means adding spaces at the start of a line to show that the line is inside a block. JavaScript does not care about indentation — your code runs the same with or without it. But humans care a lot.
Good indentation lets you see the structure of your code at a glance. Bad indentation makes even simple code hard to read.
1// ❌ Bad indentation — same code, impossible to read2function checkAge(age){if(age>=18){console.log('Adult');return true;}else{console.log('Minor');return false;}}34// ✅ Good indentation — easy to read and understand5function checkAge(age) {6 if (age >= 18) {7 console.log('Adult');8 return true;9 } else {10 console.log('Minor');11 return false;12 }13}1415console.log(checkAge(20)); // Adult, true16console.log(checkAge(15)); // Minor, false1718// ✅ Nested blocks — add 2 more spaces for each level19for (let i = 1; i <= 3; i++) {20 if (i === 2) {21 console.log('Found 2!');22 } else {23 console.log('Not 2:', i);24 }25}
- 1Use 2 spaces or 4 spaces for each level of indentation. Pick one and stick to it.
- 2Never mix spaces and tabs — it causes visual alignment problems in different editors.
- 3Each time you open a
{, add one level of indentation inside it. - 4Each time you close a
}, remove one level of indentation. - 5Install Prettier in VS Code — it auto-indents your code perfectly every time you save.
Use Prettier — never think about indentation again
Prettier is a free VS Code extension that auto-formats your code every time you save. It handles indentation, spacing, and brace placement automatically. Install it once, and your code will always be clean and readable — with zero effort.
Install: search 'Prettier' in VS Code Extensions.
Always Use Braces
Always Use Curly Braces — Even for One Line
JavaScript allows you to skip the { } if a block has only one statement. But this is a bad habit that causes real bugs.
Imagine you write an if with no braces, then later add a second line thinking it is inside the if. JavaScript will run that second line every time — whether the condition is true or false. This is a silent bug — no error, just wrong behavior.
1let isAdmin = false;23// ❌ No braces — looks fine but is dangerous4// if (isAdmin)5// console.log('Welcome, Admin!');6// deleteAllData(); ← ALWAYS RUNS — not inside the if!78// Here is what JS actually sees:9// if (isAdmin) console.log('Welcome, Admin!');10// deleteAllData(); ← completely separate statement, always runs!1112// ✅ With braces — safe and clear13if (isAdmin) {14 console.log('Welcome, Admin!');15 console.log('You have full access.');16} else {17 console.log('Access denied.');18}1920// ✅ Even for a single line — always use braces21const temperature = 38;2223if (temperature > 37) {24 console.log('You have a fever.');25}2627for (let i = 0; i < 3; i++) {28 console.log('Item:', i);29}3031console.log('Done.');
The classic brace bug
This bug has been in real software and caused serious problems:
// You write:
if (isAdmin)
showAdminPanel();
deleteUserData(); // ← you think this is inside if — IT IS NOT!
// JavaScript reads it as:
if (isAdmin) showAdminPanel();
deleteUserData(); // ← runs every time!
Always use braces. There is no reason to skip them.
Nested Blocks
Nested Blocks
A block can contain other blocks inside it. This is called nesting. For example, a for loop (a block) can contain an if statement (another block).
Each inner block adds one more level of indentation. This is how you visually show which code belongs to which block.
1// Function block → if block → nested if block2function checkScore(score) { // Level 1 block3 if (score >= 60) { // Level 2 block4 if (score >= 90) { // Level 3 block5 console.log('Excellent! Grade: A');6 } else if (score >= 75) { // Level 3 block7 console.log('Good job! Grade: B');8 } else { // Level 3 block9 console.log('Passed. Grade: C');10 }11 } else { // Level 2 block12 console.log('Failed. Please retry.');13 }14}1516checkScore(95); // Excellent! Grade: A17checkScore(80); // Good job! Grade: B18checkScore(65); // Passed. Grade: C19checkScore(40); // Failed. Please retry.2021// Loop inside a loop (nested loops)22console.log('\nMultiplication table (1-3):');23for (let i = 1; i <= 3; i++) { // outer loop block24 for (let j = 1; j <= 3; j++) { // inner loop block25 process.stdout26 ? process.stdout.write(i * j + '\t') // browser-friendly27 : console.log(i + ' x ' + j + ' = ' + (i * j));28 }29 console.log();30}
Avoid nesting too deep
When you have 4 or 5 levels of nesting, your code becomes very hard to read. This is called the pyramid of doom. If you find yourself nesting very deeply, it usually means you can split the code into smaller functions. Each function has its own clean block.
Test Your Knowledge
Test Your Knowledge
What is a code block in JavaScript?
What happens to a let variable when its block ends?
Which keyword ignores block scope and leaks out of blocks?
What is wrong with this code?
js if (isAdmin) grantAccess(); deleteAllFiles();
Why does indentation matter in JavaScript code?
Quick Reference
Code Blocks — Quick Reference
- 1A code block is statements inside
{ }. It groups them into one unit. - 2Blocks are used with
if,else,for,while,function,class,try/catch. - 3Variables created with
letorconstinside a block only exist inside that block — this is block scope. - 4
varignores block scope and leaks out — never usevarin modern JavaScript. - 5Always write
{ }braces, even when your if/else or loop has just one statement. - 6Indentation shows which code belongs to which block. Use 2 or 4 spaces per level.
- 7Never mix spaces and tabs — pick one style and stick to it.
- 8Install Prettier in VS Code — it handles indentation and braces automatically.
Statements & Semicolons
What statements are, how they work, and when to use semicolons.
Identifiers & Naming
Rules and conventions for naming variables, functions, and classes.
Variables — let, const, var
How to store values in JavaScript and the difference between let, const, and var.
Control Flow
if/else, switch, and loops — how to control what your program does.
You understand code blocks!
You now know what blocks are, where they are used, how block scope works, and why indentation matters. These are the foundations of writing clean, readable JavaScript. Always use braces, always indent, and use Prettier to automate it all.
Try it in the Javascript Compiler
Run and experiment with Javascript code right in your browser — no setup needed.