Course contentsShow
← JavaScript
Lesson 81 of 2,7233. Variables and ScopeFree lesson

Blocks vs Functions

Understanding the difference between block-level scope and function-level scope.

Blocks vs Functions

What you'll learn: You'll understand how blocks {} and functions create different types of scope in JavaScript.

The Core Difference

A block is any pair of curly braces that isn't part of a function or object. You see them in if, for, while, and standalone { } statements. A function is a reusable piece of code you define with the function keyword.

Here's the key distinction: block scope (created by blocks) only affects let and const variables. Function scope (created by functions) affects var, let, and const variables.

Why This Matters

When you declare a variable with var, it ignores block boundaries but respects function boundaries. Variables declared with let or const respect both block and function boundaries.

Think of it like security clearance levels:

  • Blocks are like rooms in a building — let and const can't leave the room they're declared in
  • Functions are like entire separate buildings — var, let, and const all stay inside their function

A block inside a function is like a room inside a building. Variables declared with let or const stay in that room. But var ignores the room walls and spreads throughout the entire building (function).

The Practical Impact

If you use var inside an if block, that variable is accessible outside the if block (but still inside any containing function). If you use let or const, the variable dies when the block ends.

Key Takeaway: Blocks create scope boundaries for let and const only; functions create scope boundaries for all variable types (var, let, and const).