EASYTUTORGUIDE

Practical tutorials, tools, courses, digital skills, and business promotion.

Free Learning

Chapter 14: JavaScript Scopes

Learn all about javascript from very beginners to experts.

Beginner Friendly Examples Output Explanation
Javascript Lesson 14 Scopes interactive Courses

Main reading content

javascript-course-chapter-14

Chapter 14: Scope

Learn JavaScript scope with explanations, fully commented code, outputs, and code explanations.

Goal: Understand where variables can be used and how JavaScript searches for variables.

Chapter 14 Topics

14.1 Global Scope

Global scope means a variable is created outside all functions and blocks. A global variable can be used from many places in the same JavaScript file. It stays available while the page or program is running. Global variables are easy to access, but they can also cause mistakes. If many functions change the same global variable, the code can become confusing. Beginners should use global variables only when the value is truly needed everywhere.

Example: Access global variable inside function

// Create a global variable outside any function.
let websiteName = "EasyTutorGuide";

// Create a function.
function showWebsiteName() {

  // Access the global variable inside the function.
  console.log(websiteName);
}

// Call the function.
showWebsiteName();
Output:
EasyTutorGuide

Code Explanation: The variable websiteName is created outside the function. Because it is in global scope, the function can access it. When showWebsiteName() runs, JavaScript prints the value. This shows that global variables can be used from inside functions.

14.2 Function Scope

Function scope means a variable exists only inside the function where it is created. Variables declared inside a function cannot be used outside that function. This protects the variable from being changed by other parts of the program. Function scope helps keep code organized and safer. Each function can have its own private variables. Beginners should use function scope when data is only needed inside one function.

Example: Variable inside function

// Create a function.
function showStudent() {

  // Create a variable inside the function.
  let studentName = "Ali";

  // Print the variable inside the function.
  console.log(studentName);
}

// Call the function.
showStudent();
Output:
Ali

Code Explanation: The variable studentName is created inside showStudent(). JavaScript can use it inside the function. The variable is private to that function. This means other parts of the code cannot directly access it outside the function.

14.3 Block Scope

Block scope means a variable exists only inside curly braces. Blocks are used in if statements, loops, and other structures. Variables declared with let and const are block scoped. This means they cannot be used outside the block where they are created. Block scope helps prevent accidental changes to variables. Modern JavaScript uses block scope often because it keeps code clean.

Example: Variable inside if block

// Create an if block.
if (true) {

  // Create a block scoped variable.
  let age = 15;

  // Print the variable inside the block.
  console.log(age);
}
Output:
15

Code Explanation: The variable age is created inside the curly braces. Because it uses let, it belongs only to that block. JavaScript can print it inside the block. Outside the block, the variable is not available.

14.4 Lexical Scope

Lexical scope means JavaScript decides scope based on where code is written. An inner function can access variables from the outer function. This happens because the inner function is written inside the outer function. JavaScript reads the structure of your code to know what variables are available. Lexical scope is very important for understanding closures later. Beginners can remember it as inner code can look outward to parent scopes.

Example: Inner function reads outer variable

// Create an outer function.
function outerFunction() {

  // Create a variable inside the outer function.
  let message = "Hello from outer function";

  // Create an inner function.
  function innerFunction() {

    // Inner function can access the outer variable.
    console.log(message);
  }

  // Call the inner function.
  innerFunction();
}

// Call the outer function.
outerFunction();
Output:
Hello from outer function

Code Explanation: The variable message is inside outerFunction(). The function innerFunction() is written inside the outer function. Because of lexical scope, the inner function can access the outer variable. JavaScript uses where code is written to decide access.

14.5 Scope Chain

The scope chain is the path JavaScript follows when searching for a variable. JavaScript first looks in the current local scope. If it does not find the variable there, it checks the outer scope. It continues moving outward until it reaches the global scope. If the variable is not found anywhere, JavaScript gives an error. Scope chain explains how inner functions can use variables from parent scopes.

Example: JavaScript searches outer scopes

// Create a global variable.
let globalMessage = "Global message";

// Create an outer function.
function outer() {

  // Create an outer function variable.
  let outerMessage = "Outer message";

  // Create an inner function.
  function inner() {

    // JavaScript finds this in the outer function scope.
    console.log(outerMessage);

    // JavaScript finds this in the global scope.
    console.log(globalMessage);
  }

  // Call the inner function.
  inner();
}

// Call the outer function.
outer();
Output:
Outer message
Global message

Code Explanation: JavaScript first checks inside inner(). It does not find outerMessage there, so it checks the outer function. It finds globalMessage in global scope. This searching path is called the scope chain.

14.6 Variable Shadowing

Variable shadowing happens when an inner scope has a variable with the same name as an outer scope. The inner variable hides the outer variable inside that scope. JavaScript always uses the closest matching variable first. Shadowing is allowed, but it can make code confusing if overused. Clear variable names help avoid shadowing mistakes. Beginners should understand shadowing so they know why values change in different places.

Example: Local variable hides global variable

// Create a global variable.
let name = "Global Ali";

// Create a function.
function showName() {

  // Create a local variable with the same name.
  let name = "Local Sara";

  // JavaScript uses the closest variable.
  console.log(name);
}

// Call the function.
showName();

// Print the global variable.
console.log(name);
Output:
Local Sara
Global Ali

Code Explanation: There are two variables named name. Inside the function, JavaScript uses the local variable first. This hides the global variable inside the function. Outside the function, JavaScript uses the global variable again.

14.7 Hoisting

Hoisting means JavaScript prepares declarations before running code. Function declarations can be called before they appear in the file. Variables created with var are hoisted, but their values are not assigned yet. Variables created with let and const are also prepared but cannot be used before declaration. Hoisting can confuse beginners when code is written out of order. A good habit is to declare variables and functions before using them.

Example: Function declaration is hoisted

// Call the function before it is written.
sayHello();

// Create a function declaration.
function sayHello() {

  // Print a message.
  console.log("Hello from hoisting!");
}
Output:
Hello from hoisting!

Code Explanation: The function is called before the function code appears. JavaScript still runs it because function declarations are hoisted. JavaScript prepares the function before execution. This works, but beginners should still write code in a clear order.

14.8 Execution Context

Execution context is the environment where JavaScript code runs. When a script starts, JavaScript creates a global execution context. When a function runs, JavaScript creates a new function execution context. Each context stores variables, functions, and scope information. JavaScript manages these contexts using the call stack. Beginners can think of execution context as a workspace for running code.

Example: Function creates its own context

// Create a global variable.
let course = "JavaScript";

// Create a function.
function showCourse() {

  // Create a local variable inside function context.
  let chapter = "Scope";

  // Print global variable.
  console.log(course);

  // Print local variable.
  console.log(chapter);
}

// Call the function.
showCourse();
Output:
JavaScript
Scope

Code Explanation: The variable course belongs to the global context. When showCourse() runs, JavaScript creates a function context. The variable chapter belongs to that function context. The function can access both local and global variables.

14.9 Closures Intro

A closure happens when an inner function remembers variables from an outer function. The outer function may finish running, but the inner function can still access its variables. Closures are possible because of lexical scope. They are useful for private data, counters, event handlers, and advanced patterns. Beginners may find closures difficult at first. The simple idea is that a function can remember where it was created.

Example: Counter using closure

// Create an outer function.
function createCounter() {

  // Create a private variable.
  let count = 0;

  // Return an inner function.
  return function() {

    // Increase the remembered count.
    count++;

    // Print the updated count.
    console.log(count);
  };
}

// Store the returned inner function.
let counter = createCounter();

// Call the inner function multiple times.
counter();
counter();
counter();
Output:
1
2
3

Code Explanation: createCounter() creates a variable named count. It returns an inner function. The inner function remembers count even after the outer function finishes. Each time counter() runs, the same remembered value increases.

14.10 Scope Best Practices

Scope best practices help keep JavaScript code clean and safe. Use const when a value should not be reassigned. Use let when a value needs to change. Avoid creating too many global variables. Keep variables close to where they are used. Clear scope habits make code easier to debug, read, and maintain.

Example: Keep variable inside function

// Create a function for tax calculation.
function calculateTotal(price) {

  // Keep taxRate inside the function because it is only used here.
  const taxRate = 0.13;

  // Calculate total price.
  const total = price + price * taxRate;

  // Return the total.
  return total;
}

// Call the function and print the result.
console.log(calculateTotal(100));
Output:
113

Code Explanation: The variable taxRate is inside the function because it is only needed there. This avoids unnecessary global variables. The function calculates the total and returns it. This keeps the code clean, safe, and reusable.

Chapter 14 Summary

  • Global scope means variables are available in many parts of the script.
  • Function scope keeps variables inside a function.
  • Block scope keeps let and const inside curly braces.
  • Lexical scope means inner code can access outer variables.
  • The scope chain is how JavaScript searches for variables.
  • Variable shadowing happens when an inner variable hides an outer variable.
  • Hoisting prepares declarations before code runs.
  • Execution context is the workspace JavaScript uses to run code.
  • Closures allow inner functions to remember outer variables.
  • Good scope habits make code cleaner and easier to debug.
Chapter 14: ScopesJavaScript Scopes

A modern course built to help learners study step by step with clarity, comfort, and confidence.