JavaScript and TypeScript course Β· Module 2: Functions, Arrays and Objects

Variable Scope (Global, Function, Block)

11 min read Β·
In this lesson8

Welcome back to Jurassic Park! Today we will tackle one of the fundamental concepts of JavaScript - variable scope. Understanding variable scope is key to writing efficient, safe and predictable code, especially in complex systems such as our park full of dinosaurs.

What Is Variable Scope?

Variable scope determines where in the code a given variable is available - in other words, from which places in the code we can refer to it. Just as Jurassic Park has zones with different access levels (the visitor zone, the laboratory for scientists only, the enclosures that require special permissions), JavaScript has different scopes of access to variables.

In JavaScript we distinguish three main types of scope:

  1. Global scope
  2. Function scope
  3. Block scope

Global Scope

Variables defined outside of any function or block of code have global scope. This means they are available throughout the whole program, in every function and every block of code.

// Global variables - available everywhere, like public information about the park
const parkName = "Jurassic Park";
let visitorCount = 0;
var isOpenToPublic = true;

function checkParkStatus() {
  console.log(`Park name: ${parkName}`);
  console.log(`Number of visitors: ${visitorCount}`);
  console.log(`Open to visitors: ${isOpenToPublic}`);
}

function updateVisitorCount(newCount) {
  // We can modify a global variable from any function
  visitorCount = newCount;
  console.log(`Number of visitors updated: ${visitorCount}`);
}

// Calling the functions that use the global variables
checkParkStatus();
updateVisitorCount(250);
checkParkStatus();

You should be careful with global variables, because:

  • They can be accidentally modified from anywhere in the code
  • They can lead to name conflicts
  • They make it harder to track the state of the application
  • They increase the coupling between different parts of the code

Global variables in our park are like documents available to all employees - sometimes they are essential, but too many such documents can lead to mess and misunderstandings.

Function Scope

Variables defined inside a function are available only inside that function. They are local variables of that function.

function monitorDinosaur(dinoId) {
  // These variables have function scope - they are available only inside this function
  const startTime = Date.now();
  let status = "Monitoring...";
  var sensorData = [];

  // We can use the variables inside the function
  status = "Collecting data...";
  sensorData.push({ time: startTime, temperature: 37.5 });

  console.log(`Status: ${status}`);
  console.log(`Sensor data: ${JSON.stringify(sensorData)}`);

  // We return the result
  return {
    id: dinoId,
    monitoringStarted: startTime,
    lastStatus: status
  };
}

// Calling the function
const monitoringResults = monitorDinosaur("T-Rex-01");

// The code below would cause an error, because we are trying to access
// variables with function scope from outside the function
// console.log(startTime);    // ReferenceError
// console.log(status);       // ReferenceError
// console.log(sensorData);   // ReferenceError

// But we do have access to the value returned by the function
console.log(monitoringResults);

Function scope works like the restricted zones in the park - only authorized personnel (the code inside the function) have access to the information and resources in that zone.

The Difference Between var, let and const in the Context of Function Scope

All three keywords (var, let, const) create variables with function scope, but there is an important difference between them:

  • var has function scope, but not block scope
  • let and const have both function scope and block scope

Let's see this in an example:

function securityCheck() {
  // All these variables are available throughout the whole function
  var securityCode = "A1B2C3";
  let accessLevel = 5;
  const securityChief = "Robert Muldoon";

  if (accessLevel >= 5) {
    var emergencyProtocol = "Code Red"; // function scope!
    let backupSystem = "Operational";   // block scope
    const safeRoom = "Bunker B";        // block scope

    console.log(securityCode);    // A1B2C3 - available
    console.log(accessLevel);     // 5 - available
    console.log(securityChief);   // Robert Muldoon - available
  }

  console.log(emergencyProtocol); // Code Red - available even though it was defined in the if block
  // console.log(backupSystem);   // ReferenceError - the variable has block scope
  // console.log(safeRoom);       // ReferenceError - the variable has block scope
}

securityCheck();

Block Scope

Block scope was introduced in ES6 (ES2015) together with the new keywords let and const. Variables defined with let and const inside a block of code (delimited by curly braces {}) are available only inside that block.

function monitorDinosaurBehavior() {
  let dangerLevel = 0;

  // The if block - creates a new scope
  if (true) {
    // Block scope - variables available only inside this block
    let behavior = "Calm";
    const vitals = { heartRate: 80, temperature: 38 };

    // Modifying a variable from the outer scope
    dangerLevel = behavior === "Aggressive" ? 5 : 1;

    console.log(behavior);     // Calm - available
    console.log(vitals);       // { heartRate: 80, temperature: 38 } - available
    console.log(dangerLevel);  // 1 - available
  }

  console.log(dangerLevel);    // 1 - available because it was defined in a wider scope
  // console.log(behavior);    // ReferenceError - the variable has block scope
  // console.log(vitals);      // ReferenceError - the variable has block scope

  // The for block - also creates a new scope
  for (let i = 0; i < 5; i++) {
    // 'i' has block scope, available only inside the loop
    const sensorId = `Sensor-${i}`;
    console.log(sensorId);
  }

  // console.log(i);        // ReferenceError - 'i' has block scope
  // console.log(sensorId); // ReferenceError - the variable has block scope
}

monitorDinosaurBehavior();

Block scope is like the individual enclosures in our park - each enclosure has its own rules and access, and the equipment assigned to one enclosure is not available in the other enclosures.

The Difference Between var, let and const

Now we can better understand the differences between these three keywords:

  1. var:

    • Has function or global scope, but not block scope
    • Can be redeclared multiple times
    • Can be modified
    • Is hoisted with the value undefined assigned to it
  2. let:

    • Has block scope
    • Cannot be redeclared in the same scope
    • Can be modified
    • Is hoisted without a value being assigned (temporal dead zone)
  3. const:

    • Has block scope
    • Cannot be redeclared in the same scope
    • Cannot be modified (but the properties of objects can be modified)
    • Is hoisted without a value being assigned (temporal dead zone)
function demonstrateVariables() {
  // var
  var dinosaur = "T-Rex";
  var dinosaur = "Velociraptor"; // OK - can be redeclared
  dinosaur = "Triceratops";      // OK - can be modified

  // let
  let park = "Jurassic Park";
  // let park = "Dino World";    // Error - cannot be redeclared
  park = "Jurassic World";       // OK - can be modified

  // const
  const island = "Isla Nublar";
  // const island = "Isla Sorna"; // Error - cannot be redeclared
  // island = "Another Island";   // Error - cannot be modified

  // But the properties of const objects can be modified
  const parkSystem = {
    mainPower: true,
    backupGenerator: false
  };

  // This is allowed
  parkSystem.mainPower = false;
  parkSystem.backupGenerator = true;

  console.log(parkSystem); // { mainPower: false, backupGenerator: true }
}

demonstrateVariables();

Lexical Scope and Closures

JavaScript uses lexical scope, which means that functions can access variables defined in their outer scope.

function initSecuritySystem() {
  // Variables in the scope of the outer function
  const systemName = "JurassicSafe";
  let isActive = false;
  let alertLevel = 0;

  // The inner function has access to the variables of the outer function
  function activateSystem() {
    isActive = true;
    console.log(`System ${systemName} has been activated.`);
    return true;
  }

  // One more inner function
  function setAlertLevel(level) {
    alertLevel = level;
    console.log(`System ${systemName}: alert level set to ${alertLevel}`);
  }

  // We return the inner functions
  return {
    activate: activateSystem,
    setAlert: setAlertLevel,
    getStatus: function() {
      return {
        name: systemName,
        active: isActive,
        alertLevel: alertLevel
      };
    }
  };
}

// We create an instance of the security system
const securitySystem = initSecuritySystem();

// We use the returned functions
securitySystem.activate();           // System JurassicSafe has been activated.
securitySystem.setAlert(3);          // System JurassicSafe: alert level set to 3
console.log(securitySystem.getStatus()); // { name: "JurassicSafe", active: true, alertLevel: 3 }

In the example above, the inner functions form a closure over the variables of the initSecuritySystem function. Even after initSecuritySystem has finished executing, the returned functions still have access to those variables.

Closures are like the security teams in the park - even when they leave the command center, they still have access to the codes and protocols they took with them.

Practical Example: A Park Management System

Let's build a more comprehensive example that demonstrates the different variable scopes in the context of a park management system:

// Global variables - available throughout the whole program
const PARK_NAME = "Jurassic Park";
let parkStatus = "closed";
var totalVisitors = 0;

// An IIFE (Immediately Invoked Function Expression) that creates a module
const parkSystem = (function() {
  // Private variables - function scope, inaccessible from outside the module
  let securityStatus = "active";
  let powerStatus = "online";
  const MAX_CAPACITY = 2000;

  // Private helper function
  function checkSystemStatus() {
    return powerStatus === "online" && securityStatus === "active";
  }

  // The module's public API
  return {
    // Method that opens the park to visitors
    openPark: function() {
      if (checkSystemStatus()) {
        parkStatus = "open"; // Modifying a global variable
        console.log(`${PARK_NAME} is now open to visitors!`);
        return true;
      } else {
        console.log("Cannot open the park - the security systems are not fully operational.");
        return false;
      }
    },

    // Method that registers new visitors
    registerVisitors: function(count) {
      // Checking the park's capacity
      if (parkStatus !== "open") {
        console.log("The park is closed. Cannot register visitors.");
        return false;
      }

      // A variable with block scope
      const availableCapacity = MAX_CAPACITY - totalVisitors;

      if (count <= availableCapacity) {
        totalVisitors += count; // Modifying a global variable
        console.log(`Registered ${count} new visitors. Total: ${totalVisitors}`);

        // Block scope inside the condition
        if (totalVisitors > MAX_CAPACITY * 0.8) {
          const warningMessage = "Warning: The park is approaching maximum capacity!";
          console.log(warningMessage);
        }

        return true;
      } else {
        console.log(`Error: Too many visitors. Available capacity: ${availableCapacity}`);
        return false;
      }
    },

    // Method that closes the park
    closePark: function() {
      // A local function with access to variables from a wider scope
      function evacuateVisitors() {
        console.log(`Evacuating ${totalVisitors} visitors from the park...`);
        totalVisitors = 0;
      }

      parkStatus = "closed";
      evacuateVisitors();
      console.log(`${PARK_NAME} has been closed.`);

      return true;
    },

    // Method that changes the status of the systems
    updateSystems: function(power, security) {
      // To demonstrate let vs var
      if (power) {
        let localMessage = "Updating the power system...";
        console.log(localMessage);
        powerStatus = power;
      }

      if (security) {
        var statusMessage = "Updating the security system...";
        console.log(statusMessage);
        securityStatus = security;
      }

      // console.log(localMessage); // Error: localMessage has block scope
      console.log(statusMessage);  // Works: statusMessage has function scope

      return {
        power: powerStatus,
        security: securityStatus
      };
    }
  };
})();

// Using our system
console.log(`Park status before opening: ${parkStatus}`);
parkSystem.openPark();
console.log(`Park status after opening: ${parkStatus}`);

parkSystem.registerVisitors(500);
parkSystem.registerVisitors(1200);  // Should show a capacity warning
parkSystem.registerVisitors(400);   // Should show an error about exceeding capacity

// Updating the systems
parkSystem.updateSystems("offline", null);
parkSystem.openPark(); // Should show an error - the park cannot be opened

// Restoring the systems and closing the park
parkSystem.updateSystems("online", "active");
parkSystem.closePark();
console.log(`Park status after closing: ${parkStatus}`);
console.log(`Number of visitors after the evacuation: ${totalVisitors}`);

// Trying to access the private variables
// console.log(securityStatus); // Error: variable not accessible
// console.log(MAX_CAPACITY);   // Error: variable not accessible

Good Practice Rules

  1. Avoid global variables - just like in a real park, the more public areas there are, the harder they are to monitor and secure.

  2. Prefer const over let, and let over var - most variables should not change their values, and if they do, they should have the smallest possible scope.

  3. Use block scope - limit the visibility of variables to the smallest possible scope.

  4. Apply the module pattern - encapsulate variables and functions in modules, exposing only the necessary API.

  5. Be aware of closures - closures are a powerful tool, but they can lead to memory leaks if they are used incorrectly.

Summary

Variable scope in JavaScript is like the system of access zones in Jurassic Park:

  • Global scope - like the public areas of the park, available to everyone
  • Function scope - like the zones restricted to specific employees
  • Block scope - like the individual enclosures and laboratories with their own access system

Understanding variable scope lets us write better organized, safer and more predictable code - just as good zone management in a park full of dangerous dinosaurs makes everyone safer.

In one of the upcoming lessons we will dive into hoisting, which is closely related to variable scope and has a significant impact on how JavaScript code works.

Code for this lesson: index.js
// Variable Scope - Jurassic Park
console.log("Variable Scope Laboratory");
console.log("Understanding scope in JavaScript\n");

// ===========================================
// 1. GLOBAL SCOPE
// ===========================================
console.log("=== 1. Global scope ===");

const parkName = "Jurassic Park"; // Global variable
let totalDinosaurs = 0; // Global variable

function addDinosaur(name) {
  totalDinosaurs++; // Access to global variable
  console.log(`Added ${name}. Total dinosaurs: ${totalDinosaurs}`);
  console.log(`   In the park: ${parkName}`);
}

addDinosaur("T-Rex");
addDinosaur("Velociraptor");
addDinosaur("Triceratops");

console.log(`\nPark ${parkName} has ${totalDinosaurs} dinosaurs`);

// ===========================================
// 2. FUNCTION SCOPE
// ===========================================
console.log("\n=== 2. Function scope ===");

function feedDinosaur(dinoName) {
  const foodAmount = 50; // Local variable of the function
  const message = `Feeding ${dinoName} (portion: ${foodAmount}kg)`;

  console.log(`${message}`);
  return foodAmount;
}

feedDinosaur("T-Rex");
feedDinosaur("Velociraptor");

// console.log(foodAmount); // ERROR: foodAmount is not defined
// console.log(message); // ERROR: message is not defined

// ===========================================
// 3. BLOCK SCOPE (let & const)
// ===========================================
console.log("\n=== 3. Block scope (let & const) ===");

function checkSecurity(sector) {
  console.log(`\nChecking security of sector ${sector}`);

  if (sector === "A") {
    let dangerLevel = "HIGH"; // Block-scoped variable
    const dinosaurType = "T-Rex"; // Block-scoped variable

    console.log(`   Danger level: ${dangerLevel}`);
    console.log(`   Dinosaur type: ${dinosaurType}`);
  }

  // console.log(dangerLevel); // ERROR: dangerLevel is not defined
  // console.log(dinosaurType); // ERROR: dinosaurType is not defined

  console.log(`   Sector ${sector} check completed`);
}

checkSecurity("A");
checkSecurity("B");

// Example with for loop
console.log("\nLoop with let:");
for (let i = 0; i < 3; i++) {
  console.log(`  Iteration ${i + 1}`);
}
// console.log(i); // ERROR: i is not defined

// ===========================================
// 4. var vs let vs const
// ===========================================
console.log("\n=== 4. Differences: var vs let vs const ===");

function demonstrateScope() {
  console.log("\nScope demonstration:");

  // var - function scope (old way)
  if (true) {
    var dinoVar = "T-Rex (var)";
    let dinoLet = "Velociraptor (let)";
    const dinoConst = "Triceratops (const)";

    console.log(`  In block - var: ${dinoVar}`);
    console.log(`  In block - let: ${dinoLet}`);
    console.log(`  In block - const: ${dinoConst}`);
  }

  console.log(`\n  Outside block - var: ${dinoVar}`); // Works!
  // console.log(`  Outside block - let: ${dinoLet}`); // ERROR
  // console.log(`  Outside block - const: ${dinoConst}`); // ERROR
}

demonstrateScope();

// ===========================================
// 5. CLOSURE
// ===========================================
console.log("\n=== 5. Closures ===");

function createDinosaurCounter(startCount = 0) {
  let count = startCount; // Private variable

  return {
    add: function(name) {
      count++;
      console.log(`Added ${name}. Count: ${count}`);
    },
    remove: function(name) {
      if (count > 0) {
        count--;
        console.log(`Removed ${name}. Count: ${count}`);
      }
    },
    getCount: function() {
      return count;
    }
  };
}

const sectorA = createDinosaurCounter(5);
const sectorB = createDinosaurCounter(0);

console.log("\nSector A:");
sectorA.add("T-Rex");
sectorA.add("Velociraptor");
console.log(`Total in sector A: ${sectorA.getCount()}`);

console.log("\nSector B:");
sectorB.add("Triceratops");
console.log(`Total in sector B: ${sectorB.getCount()}`);

// ===========================================
// 6. NESTED FUNCTIONS
// ===========================================
console.log("\n=== 6. Nested functions and scope ===");

function managePark() {
  const parkName = "Isla Nublar";
  let visitors = 1000;

  function openPark() {
    console.log(`\n${parkName} open for ${visitors} visitors`);

    function welcomeVisitors() {
      visitors += 50;
      console.log(`   Greeting new visitors. Now: ${visitors}`);
    }

    welcomeVisitors();
  }

  function closePark() {
    console.log(`\nClosing ${parkName}`);
    console.log(`   Today's visitors: ${visitors}`);
  }

  openPark();
  closePark();
}

managePark();

// ===========================================
// 7. SHADOWING
// ===========================================
console.log("\n=== 7. Shadowing (variable shadowing) ===");

const dinosaur = "T-Rex (global)";

function checkDinosaur() {
  const dinosaur = "Velociraptor (function)"; // Shadows global
  console.log(`In function: ${dinosaur}`);

  if (true) {
    const dinosaur = "Triceratops (block)"; // Shadows function
    console.log(`   In block: ${dinosaur}`);
  }

  console.log(`   After block: ${dinosaur}`);
}

console.log(`Globally: ${dinosaur}`);
checkDinosaur();
console.log(`Again globally: ${dinosaur}`);

// ===========================================
// 8. LEXICAL SCOPE
// ===========================================
console.log("\n=== 8. Lexical scope ===");

const habitat = "Tropical forest";

function outerFunction() {
  const temperature = 28;

  function innerFunction() {
    const humidity = 80;

    // Access to all variables from parent scopes
    console.log(`Environment: ${habitat}`);
    console.log(`   Temperature: ${temperature}Β°C`);
    console.log(`   Humidity: ${humidity}%`);
  }

  innerFunction();
}

outerFunction();

// ===========================================
// 9. PRACTICAL EXAMPLE - FEEDING SYSTEM
// ===========================================
console.log("\n=== 9. Feeding system - practical example ===");

function createFeedingSystem() {
  const feedingSchedule = [];
  let lastFeedingTime = null;

  return {
    scheduleFeed: function(dinoName, time) {
      const entry = { dino: dinoName, time: time, completed: false };
      feedingSchedule.push(entry);
      console.log(`Feeding scheduled for: ${dinoName} at ${time}`);
    },

    completeFeed: function(dinoName) {
      const entry = feedingSchedule.find(e => e.dino === dinoName && !e.completed);
      if (entry) {
        entry.completed = true;
        lastFeedingTime = new Date().toLocaleTimeString();
        console.log(`Fed ${dinoName} at ${lastFeedingTime}`);
      } else {
        console.log(`No feeding scheduled for ${dinoName}`);
      }
    },

    getReport: function() {
      console.log("\nFEEDING REPORT:");
      console.log(`   Last feeding: ${lastFeedingTime || "None"}`);
      console.log(`   Scheduled feedings: ${feedingSchedule.length}`);

      const pending = feedingSchedule.filter(e => !e.completed);
      if (pending.length > 0) {
        console.log("\n   Pending:");
        pending.forEach(e => {
          console.log(`     - ${e.dino} at ${e.time}`);
        });
      }
    }
  };
}

const feedingSystem = createFeedingSystem();

feedingSystem.scheduleFeed("T-Rex", "08:00");
feedingSystem.scheduleFeed("Velociraptor", "10:00");
feedingSystem.scheduleFeed("Triceratops", "12:00");

feedingSystem.completeFeed("T-Rex");
feedingSystem.completeFeed("Velociraptor");

feedingSystem.getReport();

// ===========================================
// 10. BEST PRACTICES
// ===========================================
console.log("\n=== 10. Best practices ===");

// GOOD: Use const for values that don't change
const MAX_DINOSAURS = 50;
console.log(`Maximum number of dinosaurs: ${MAX_DINOSAURS}`);

// GOOD: Use let for changeable values
let currentDinoCount = 15;
currentDinoCount += 5;
console.log(`Current count: ${currentDinoCount}`);

// BAD: Avoid var (old way)
// var oldStyle = "Not recommended";

// GOOD: Limit variable scope to minimum
function goodScope() {
  const onlyHere = "Available only here";
  return onlyHere;
}

console.log("\nCongratulations! You've mastered variable scope!");

Docs entries used in this lesson

Spotted a mistake in this lesson?

Check yourself

Answer the questions from this lesson. Pick an answer to see right away whether it is correct.

  1. 1. Which variable declaration is best for a constant dinosaur species value?

  2. 2. What will the following code return: String(65000000)?

  3. 3. Dr. Wu is organizing data in the lab. Which data-to-JavaScript-type match is INCORRECT?

Hands-on tasks in the game

  • Code editor

    Form data is always text: const inputWeight = '6200', const inputLength = '9.5' and const inputTeeth = '800'. Convert them to numbers: numWeight with Number(), numLength with parseFloat() and numTeeth with parseInt(). Then store numWeight back as text in weightText with String(). Display all four values in the console together with their type (typeof).

  1. QuestionConst vs Let vs Var
  2. QuestionType Conversion
  3. Coding taskExercise: Type Conversion
  4. QuestionMatching Data Types

Useful articles