Function Scope


Function Scope: Variables declared with var

In JavaScript, when you declare a variable using var inside a function, that variable is confined to the function's scope. This means it is only accessible within that function and not from outside. This concept is fundamental to managing variables and avoiding naming conflicts in your code.


Example 1: Basic Function Scope

// A function demonstrating basic function scope
function showName() {
  // 'playerName' is only available inside this showName function
  var playerName = "Alice";
  console.log(playerName); // Output: Alice
}

showName();
// console.log(playerName); // This would cause a ReferenceError because playerName is not defined here

Explanation

The variable playerName is declared with var inside the showName function. It can be successfully accessed within that function, but attempting to access it outside results in an error.


Example 2: No Block Scope for var

// Demonstrating that 'var' does not have block scope
function blockScopeTest() {
  if (true) {
    // 'playerScore' is function-scoped, not block-scoped
    var playerScore = 100;
  }
  console.log(playerScore); // Output: 100
}

blockScopeTest();

Explanation

Even though playerScore is declared inside an if block, var makes it accessible throughout the entire blockScopeTest function. This is a key difference between var and newer keywords like let and const.


Example 3: Function Scope with Parameters

// Function parameters also have function scope
function greetPlayer(playerName) {
  // 'greeting' is function-scoped
  var greeting = "Hello, " + playerName;
  console.log(greeting);
}

greetPlayer("Bob"); // Output: Hello, Bob
// console.log(greeting); // This would result in a ReferenceError

Explanation

The parameter playerName and the variable greeting are both scoped to the greetPlayer function. They cannot be accessed from outside the function's definition.


Example 4: Nested Functions

// Demonstrating scope in nested functions
function outerFunction() {
  var outerVar = "I am outside!";

  function innerFunction() {
    // The inner function can access variables from the outer function
    console.log(outerVar); // Output: I am outside!
  }

  innerFunction();
}

outerFunction();

Explanation

The innerFunction has access to the variables declared in its parent, outerFunction. This concept is known as a closure, where the inner function "closes over" the parent's scope.


Example 5: Variable Hoisting with var

// 'var' declarations are hoisted to the top of their scope
function hoistingExample() {
  console.log(game); // Output: undefined
  var game = "Chess";
  console.log(game); // Output: Chess
}

hoistingExample();

Explanation

JavaScript "hoists" var declarations to the top of their function scope. This means the variable game is declared for the entire function, but its assignment (= "Chess") only happens at that line, which is why the first log is undefined.


Example 6: Overwriting Global Variables

// A global variable
var score = 50;

function updateScore() {
  // This 'score' is local to the function due to the 'var' keyword
  var score = 100;
  console.log(score); // Output: 100
}

updateScore();
console.log(score); // Output: 50

Explanation

Inside updateScore, a new score variable is created that is local to that function, effectively "shadowing" the global score. The global score remains unchanged.


Example 7: For Loop Scope with var

// Demonstrating the scope of 'var' within a for loop
function loopScope() {
  for (var i = 0; i < 3; i++) {
    // The loop is running
  }
  console.log(i); // Output: 3
}

loopScope();

Explanation

The variable i, declared with var in the for loop, is scoped to the entire loopScope function. This is why it's accessible after the loop has finished, holding its final value.