javascript

Code Blocks and Indentation

Learn what code blocks are in JavaScript, how curly braces group statements, why indentation matters, and how scope works inside blocks.

12 min read 9 sections Tutorial
Share

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 block
  • for (let i = 0; i < 5; i++) { ... } — loop block
  • function greet() { ... } — function block
  • class 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.

javascript
1// A block with if — runs only when condition is true
2let temperature = 35;
3
4if (temperature > 30) {
5 console.log('It is hot outside.'); // ← inside the block
6 console.log('Drink water!'); // ← also inside the block
7} // ← block ends here
8
9// A block with for — runs repeatedly
10for (let i = 1; i <= 3; i++) {
11 console.log('Step', i);
12}
13
14// A block with a function
15function greet(name) {
16 const message = 'Hello, ' + name + '!';
17 console.log(message);
18}
19
20greet('Alice');
21greet('Bob');
22
23// 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.

javascript
1// 1. if / else
2const score = 72;
3if (score >= 90) {
4 console.log('Grade: A');
5} else if (score >= 70) {
6 console.log('Grade: C'); // this one runs
7} else {
8 console.log('Grade: F');
9}
10
11// 2. for loop
12for (let i = 0; i < 3; i++) {
13 console.log('Count:', i);
14}
15
16// 3. while loop
17let count = 3;
18while (count > 0) {
19 console.log('Countdown:', count);
20 count--;
21}
22
23// 4. function
24function add(a, b) {
25 const result = a + b;
26 return result;
27}
28console.log('3 + 4 =', add(3, 4));
29
30// 5. try / catch
31try {
32 const data = JSON.parse('{ bad json }');
33} catch (error) {
34 console.log('Error caught:', error.message);
35}
36
37// 6. class
38class 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();
ContextSyntaxBlock ends with ;?
if / elseif (condition) { }No
for loopfor (...) { }No
while loopwhile (condition) { }No
do...whiledo { } while (condition);Yes — the while part
functionfunction name() { }No
classclass Name { }No
try / catchtry { } 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.

javascript
1// Variables declared OUTSIDE a block — available everywhere below
2let globalMessage = 'I am outside';
3
4if (true) {
5 // Variables declared INSIDE the block — only available here
6 let insideMessage = 'I am inside the if block';
7 const insideValue = 42;
8
9 console.log(globalMessage); // ✅ can access outside variable
10 console.log(insideMessage); // ✅ can access inside variable
11 console.log(insideValue); // ✅ can access inside constant
12}
13
14console.log(globalMessage); // ✅ still works
15// console.log(insideMessage); // ❌ ReferenceError — does not exist here
16// console.log(insideValue); // ❌ ReferenceError — does not exist here
17
18// Same with loops
19for (let i = 0; i < 3; i++) {
20 let loopMessage = 'iteration ' + i;
21 console.log(loopMessage);
22}
23// console.log(loopMessage); // ❌ ReferenceError — gone after the loop
24// console.log(i); // ❌ ReferenceError — i is block-scoped too
25
26console.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.

javascript
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 scope
6
7// 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); // ❌ ReferenceError
13
14// const — same as let for scope
15if (true) {
16 const fixed = 'I stay inside too.';
17 console.log(fixed); // 'I stay inside too.'
18}
19// console.log(fixed); // ❌ ReferenceError
20
21// var also leaks out of for loops!
22for (var j = 0; j < 3; j++) {
23 // j is var — it leaks
24}
25console.log('var j after loop:', j); // 3 — leaked out!
26
27for (let k = 0; k < 3; k++) {
28 // k is let — stays inside
29}
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.

javascript
1// ❌ Bad indentation — same code, impossible to read
2function checkAge(age){if(age>=18){console.log('Adult');return true;}else{console.log('Minor');return false;}}
3
4// ✅ Good indentation — easy to read and understand
5function checkAge(age) {
6 if (age >= 18) {
7 console.log('Adult');
8 return true;
9 } else {
10 console.log('Minor');
11 return false;
12 }
13}
14
15console.log(checkAge(20)); // Adult, true
16console.log(checkAge(15)); // Minor, false
17
18// ✅ Nested blocks — add 2 more spaces for each level
19for (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}
Pro Tips
  • 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.

javascript
1let isAdmin = false;
2
3// ❌ No braces — looks fine but is dangerous
4// if (isAdmin)
5// console.log('Welcome, Admin!');
6// deleteAllData(); ← ALWAYS RUNS — not inside the if!
7
8// Here is what JS actually sees:
9// if (isAdmin) console.log('Welcome, Admin!');
10// deleteAllData(); ← completely separate statement, always runs!
11
12// ✅ With braces — safe and clear
13if (isAdmin) {
14 console.log('Welcome, Admin!');
15 console.log('You have full access.');
16} else {
17 console.log('Access denied.');
18}
19
20// ✅ Even for a single line — always use braces
21const temperature = 38;
22
23if (temperature > 37) {
24 console.log('You have a fever.');
25}
26
27for (let i = 0; i < 3; i++) {
28 console.log('Item:', i);
29}
30
31console.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.

javascript
1// Function block → if block → nested if block
2function checkScore(score) { // Level 1 block
3 if (score >= 60) { // Level 2 block
4 if (score >= 90) { // Level 3 block
5 console.log('Excellent! Grade: A');
6 } else if (score >= 75) { // Level 3 block
7 console.log('Good job! Grade: B');
8 } else { // Level 3 block
9 console.log('Passed. Grade: C');
10 }
11 } else { // Level 2 block
12 console.log('Failed. Please retry.');
13 }
14}
15
16checkScore(95); // Excellent! Grade: A
17checkScore(80); // Good job! Grade: B
18checkScore(65); // Passed. Grade: C
19checkScore(40); // Failed. Please retry.
20
21// Loop inside a loop (nested loops)
22console.log('\nMultiplication table (1-3):');
23for (let i = 1; i <= 3; i++) { // outer loop block
24 for (let j = 1; j <= 3; j++) { // inner loop block
25 process.stdout
26 ? process.stdout.write(i * j + '\t') // browser-friendly
27 : 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

Quick Check

What is a code block in JavaScript?

Quick Check

What happens to a let variable when its block ends?

Quick Check

Which keyword ignores block scope and leaks out of blocks?

Quick Check

What is wrong with this code? js if (isAdmin) grantAccess(); deleteAllFiles();

Quick Check

Why does indentation matter in JavaScript code?

Quick Reference

Code Blocks — Quick Reference

Pro Tips
  • 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 let or const inside a block only exist inside that block — this is block scope.
  • 4var ignores block scope and leaks out — never use var in 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.
Continue Learning

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.

Continue Learning