/blɑk skoʊp/

noun … “Variables confined to a specific block of code.”

Block Scope is a scoping rule in which variables are only accessible within the block in which they are declared, typically defined by curly braces { } or similar delimiters. This contrasts with function or global scope, limiting variable visibility and reducing unintended side effects. Block Scope is widely used in modern programming languages like JavaScript (let, const), C++, and Java.

Key characteristics of Block Scope include:

  • Encapsulation: variables declared within a block are inaccessible outside it.
  • Shadowing: inner blocks can define variables with the same name as outer blocks, temporarily overriding the outer variable.
  • Temporal dead zone: in languages like JavaScript, let and const variables are not accessible before their declaration within the block.
  • Memory management: block-scoped variables are typically garbage collected or released once the block execution completes.
  • Supports lexical scoping: inner functions or closures can capture block-scoped variables if they are defined within the block.

Workflow example: In JavaScript:

function example() {
    let x = 10
    if (true) {
        let y = 20
        print(x + y)  -- Accessible: 30
    }
    print(y)  -- Error: y is not defined outside the block
}

example()

Here, y exists only inside the if block, while x is accessible throughout the example function. Attempting to access y outside its block results in an error.

Conceptually, Block Scope is like a private workspace within a larger office. You can organize tools and materials for a specific task without affecting other parts of the office, and once the task ends, the workspace is cleared.

See Scope, Lexical Scoping, Closure, Variable Hoisting.