CodeBlanks Logo Icon CodeBlanks

Block scope

JavaScript course · Intermediate · Lesson 9/134

Learn block-scoped variables with let and const and how they differ from var.

Block scope

Block scope means that variables declared inside a { } block are valid only inside that block. let and const are block-scoped; whatever you put inside an if, a for, or just a { } cannot be reached from outside the block.

For example, when you write if (ready) { let status = 'active'; }, status lives only inside that if block. This is a clean way to keep variables only where they are needed.

var is not block-scoped

Variables declared with var are not block-scoped; they live throughout the function they belong to. So if you write var inside an if block, that variable is also reachable from outside the block.

This old behavior causes surprising bugs today. That is why modern code uses let and const instead of var. You will see var only when reading old code.

Exercise Use a block-scoped variable

Define a function called checkStock(count). Inside an if (count > 0) block, declare a variable named let status and set its value to "in stock". In the same block, log it with console.log(status). Outside, make a checkStock(5) call.

Show example solution
function checkStock(count) {
  if (count > 0) {
    let status = "in stock";
    console.log(status);
  }
}

checkStock(5);

Test yourself

  1. What does this code output?

    if (true) {
      let x = 5;
    }
    console.log(x);
    • 5
    • ReferenceError
    • undefined
    • null
    Show answer

    ReferenceError — Correct. x declared with let is block-scoped and cannot be reached outside.

  2. Complete the block-scoped variable

    if (active) {
      let status = ____;
      console.log(status);
    }
    Show answer
    if (active) {
      let status = "active";
      console.log(status);
    }
  3. Match the declaration to its scope

    let
    Block-scoped
    const
    Block-scoped, constant
    var
    Function-scoped
    function parameter
    Only inside the function

All lessons in Intermediate