J

JavaScript Handbook

Clean • Professional

JavaScript Code Blocks & Scope – Block Scope, let, const

2 minute

JavaScript Code Blocks and Scope

In JavaScript, a code block is a section of code wrapped in {} curly braces. Code blocks are used to group statements together, control the execution flow, and define the scope of variables.

1. Block Scope

Before ES6, JavaScript only had function scope for variables declared with var. Variables declared with var could leak outside blocks like if or for, causing unexpected behavior.

ES6 introduced let and const, which provide block-level scope, meaning the variable exists only inside the block where it was defined.

Syntax:

{
  // code block
  let x = 10;
  const y = 20;
  var z = 30; // function scoped, not block scoped
}

Example 1: Block scope with let/const

{
  let name = "Alice";
  const age = 25;
  console.log(name, age); // Alice 25
}
console.log(name); // ReferenceError: name is not defined
console.log(age);  // ReferenceError: age is not defined

Example 2: var vs let inside a block

{
  var x = 10;
  let y = 20;
}
console.log(x); // 10 (var is function/global scoped)
console.log(y); // ReferenceError: y is not defined (let is block scoped)

2. Code Blocks in Control Structures

Code blocks are often used in control structures such as if, for, while, and switch to group multiple statements.

Syntax:

if (condition) {
  // multiple statements
}

for (let i = 0; i < 5; i++) {
  // multiple statements
}

Example 1: if statement block

let age = 18;
if (age >= 18) {
  let status = "Adult";
  console.log(status); // Adult
}
console.log(status); // ReferenceError: status is not defined

Example 2: for loop block

for (let i = 0; i < 3; i++) {
  const square = i * i;
  console.log(square);
}
// Output: 0, 1, 4
console.log(i);      // ReferenceError: i is not defined
console.log(square); // ReferenceError: square is not defined

Example 3: while loop block

let count = 0;
while (count < 3) {
  let message = `Count is ${count}`;
  console.log(message);
  count++;
}
// message is not accessible outside the while block

Example 4: switch case with blocks

let fruit = "apple";
switch(fruit) {
  case "apple": {
    let color = "red";
    console.log(color); // red
    break;
  }
  case "banana": {
    console.log("yellow");
    break;
  }
}
// color is not accessible outside the case block

 

Article 0 of 0