JS Global Scope

JavaScript Global Scope Variables: var, let, and const

When we’re learning JavaScript, one of the most important concepts you’ll encounter is the global scope. This refers to the area where variables live in a program, and it’s essential to understand how variables behave in different types of scopes. In JavaScript, there are three main ways to declare a variable: var, let, and const. Each has its own rules, especially when it comes to the global scope.

What is the Global Scope?

The global scope is the outermost layer of your JavaScript program. Think of it as the “big box” where variables can live, and they are accessible from anywhere inside the program. In a browser, the global scope is typically represented by the window object.

If you declare a variable in the global scope, it can be accessed anywhere in your program, even inside functions or other blocks of code.

Comparison Table: var, let, and const

Feature var let const
Scope Global or function scope Block scope Block scope
Hoisting Yes, but initialized as undefined Yes, but can’t be accessed before declaration Yes, but can’t be accessed before declaration
Re-declaration Allowed Not allowed Not allowed
Re-assignment Allowed Allowed Not allowed
Global Object Added as a property of window (in browsers) Not added to global object Not added to global object

1. var - The Old School Variable Declaration

var is the oldest way to declare a variable in JavaScript. It has some unique behaviors that can be confusing, especially when used in the global scope.

Key Characteristics of var:

•   Global Scope (when used outside a function): If you declare a variable with var in the global scope, it is added as a property of the window object in a browser.

•  Hoisting: This means that var declarations are “moved” to the top of their scope during the execution phase. This can lead to some unexpected results.

•   Re-declaration Allowed: You can re-declare the same variable multiple times, which can cause problems if you’re not careful.

Example:

var name = “Alice”; // Declaring a variable in the global scope
console.log(name); // Outputs: Alice
// Later in the code:
var name = “Bob”; // Re-declaring the same variable
console.log(name); // Outputs: Bob

1. First Declaration:

var name = “Alice”;

Here, you are declaring a variable called name using the var keyword and initializing it with the value “Alice”.

The var keyword declares the variable in the global scope (or the function scope, if inside a function). Since there is no var inside any function in your code, it is declared in the global scope.

After this line, the value of the name variable is “Alice”, and it’s accessible in the global scope.

2. First console.log:

console.log(name);

This console.log prints the current value of the name. Since the name was just set to “Alice”, the output will be:

First-console-log
3. Second Declaration:

console.log(name);

Now, you are re-declaring the variable name using the var keyword, and assigning it a new value: “Bob”.

Since var declarations are hoisted to the top of their scope, the JavaScript engine doesn’t treat this as an error. In fact, var allows you to re-declare the same variable without any issue (though it’s generally not considered good practice to re-declare variables with var in the same scope).

After this line, the value of name is now “Bob”.

4. Second console.log:

console.log(name);

This console.log prints the current value of name, which is now “Bob”.

So the output will be:
Second-console
Output:

2. let - The Block Scoped Variable

let was introduced in ECMAScript 6 (ES6) and is an improvement over var. It has a few key differences that make it safer and more predictable to use.

Key Characteristics of let:

   Global Scope (when used outside a function): If you declare a variable with let in the global scope, it doesn’t automatically become a property of the window object. This         helps avoid cluttering the global scope.

   Block Scope: Unlike var, let is block-scoped. This means the variable is only accessible inside the block (such as inside loops, if statements, or functions) where it is                  declared.

   No Hoisting (in the traditional sense): While let declarations are technically hoisted, you cannot access them before the line of code where they are defined, leading to            fewer bugs.

Example:

let name = “Alice”; // Declaring a variable in the global scope
console.log(name); // Outputs: Alice

// Later in the code:
let name = “Bob”; // SyntaxError: Identifier ‘name’ has already been declared

Code Explanation

1. First Declaration:

let name = “Alice”;

Here, the variable name is declared using the let keyword and initialized with the value “Alice”.

The let keyword creates a block-scoped variable, meaning it is only accessible within the block of code (like within a function, loop, or conditional) where it is defined.

In your case, since it’s declared in the global scope (outside of any block), name will be accessible throughout the global context, but only in that scope.

2. First console.log:

console.log(name);

This logs the value of name, which is currently “Alice”.

So, the output at this point is:
3. Second Declaration (Error):

let name = “Bob”; // SyntaxError: Identifier ‘name’ has already been declared

Here, you are trying to declare the variable name again using let, but it causes an error.

Why?

   Unlike var, let does not allow you to re-declare a variable in the same scope. If you try to declare a variable with a let that has already been declared in the same scope,      JavaScript will throw a SyntaxError.

•   In this case, the variable name has already been declared with let in the global scope, so attempting to declare it again with let causes the error.

Output:
Second-Declaration

In this example, trying to redeclare the name with let will result in an error. This prevents unintentional re-declarations and makes your code easier to debug.

Output:
Second-declaration-output
Block Scope Example:

if (true) {
let greeting = “Hello, World!”;
console.log(greeting); // Outputs: Hello, World!
}
console.log(greeting); // ReferenceError: greeting is not defined

Code explanation

1. Inside the if block:

if (true) {
let greeting = “Hello, World!”;
console.log(greeting); // Outputs: Hello, World!
}

In this block, you are declaring a variable greeting using let, and assigning it the string “Hello, World!”.

The let declaration creates a block-scoped variable. This means that the variable greeting only exists inside the {} of the if block.

The console.log(greeting) inside the block will output “Hello, World!” because the variable greeting is accessible within the block scope.

Output:
Inside-the
2. Outside the block:

console.log(greeting); // ReferenceError: greeting is not defined

After the if block, you try to log greeting again outside of the block.

However, greeting is not accessible outside the block because let has block scope. This means that the greeting variable is only valid within the {} where it was declared (the if block). Once the block is finished executing, the variable greeting is no longer accessible.

Since greeting is not defined in the global or outer scope, trying to access it here results in a ReferenceError:
outside-the-block
Output:
Outside-the-block-output

3. const - The Constant Variable Declaration

const is similar to let, but with one important difference: once a variable is declared with const, its value cannot be reassigned.

Key Characteristics of const:

   Global Scope (when used outside a function): Just like let, a const variable declared in the global scope won’t become a property of the window object.

   Block Scope: Like let, const is also block-scoped.

   Read-Only: A const variable must be assigned a value at the time of declaration, and that value cannot be changed later in the program.

Example:

const name = “Alice”; // Declaring a constant variable
console.log(name); // Outputs: Alice

// Trying to reassign:
name = “Bob”; // TypeError: Assignment to constant variable.

Code explanation

1. First Declaration:

const name = “Alice”;

Here, you’re using the const keyword to declare a variable called name and assign it the value “Alice”.

const is used to create a constant variable, which means that the variable cannot be reassigned to a new value after it has been initialized.

It’s important to note that const creates a block-scoped variable, similar to let, meaning it is only accessible within the block (such as a function, loop, or if statement) where it is declared.

In this case, since name is declared in the global scope, it will be accessible globally, but the key behavior is that its value cannot be changed after assignment.

2. First console.log:

console.log(name); // Outputs: Alice

This logs the value of the name variable, which is currently “Alice”.

So, the output at this point is:
3. Reassigning the const variable:

name = “Bob”; // TypeError: Assignment to constant variable.

Now, you’re trying to reassign name to the value “Bob”.

Since name was declared with const, this assignment is not allowed.

Why?

    A const variable cannot be reassigned after it has been initialized. Attempting to do so results in a TypeError in JavaScript.

    The specific error message you get is:

Output:

Course Video

Practice Scenario

1. Create a global variable username and write a function greetUser that logs a greeting message using the username.

–  Create a Global Variable: Declare a variable called username in the global scope.
–  Write a Function: Write a function named greetUser that logs a greeting message using the global variable username.

Here’s an example program:

// Step 1: Create a global variable username
let username = “John”;
// Step 2: Write a function greetUser
function greetUser() {
// Inside the function, use the global variable username to log a greeting message
console.log(“Hello, ” + username + “!”);
}
// Example usage
greetUser(); // Output: Hello, John!

Output:
2. Create a global variable userDetails as an object with name and age properties. Write a function displayUserDetails that logs the details using the global variable.

–  Create a Global Variable as an Object: Declare a variable called `userDetails` in the global scope, and set it as an object with properties name and age.
–  Write a Function: Write a function named displayUserDetails that logs the details using the global variable userDetails.

Here’s an example program:

// Step 1: Create a global variable userDetails as an object
let userDetails = {
name: “Alice”,
age: 25
};
// Step 2: Write a function displayUserDetails
function displayUserDetails() {
// Inside the function, use the global variable userDetails to log the details
console.log(“Name: ” + userDetails.name + “, Age: ” + userDetails.age);
}
// Example usage
displayUserDetails(); // Output: Name: Alice, Age: 25

Output:
Global-Variable-output
3. Write a program that uses all three types of variable declarations (let, const, var) in different scopes – global scope, function scope, and block scope. Create a set of variables with the same name in each scope and try to log or modify them from different parts of the program. Observe and explain the behavior of each variable type in different scopes.

The task is to understand and demonstrate the behavior of different variable declarations (let, const, and var) in various scopes (global, function, and block).

1. Global Scope:
– Declare a variable with the same name using each type (let, const, and var) in the global scope.
– Try to log or modify these variables from different parts of the program.
2. Function Scope:
– Declare a function and inside that function, declare a variable with the same name using each type (let, const, and var).
– Try to log or modify these variables within and outside the function.
3. Block Scope:
– Declare a block of code (e.g., inside an `if` statement or `for` loop) and inside that block, declare a variable with the same name using each type (let, const, and var).
– Try to log or modify these variables within and outside the block.
4. Observe and Explain: Observe and explain the behavior of each variable type in different scopes. Understand how they behave when trying to log or modify them from various parts of the program.

Here’s an example program:

// Global scope
let globalLetVar = “Global let”;
const globalConstVar = “Global const”;
var globalVarVar = “Global var”;
function exampleFunction() {
// Function scope
let functionLetVar = “Function let”;
const functionConstVar = “Function const”;
var functionVarVar = “Function var”;
if (true) {
// Block scope
let blockLetVar = “Block let”;
const blockConstVar = “Block const”;
var blockVarVar = “Block var”;
console.log(globalLetVar); // Access globalLetVar from block
console.log(functionLetVar); // Access functionLetVar from block
console.log(blockLetVar); // Log blockLetVar
}
console.log(globalConstVar); // Access globalConstVar from function
console.log(functionConstVar); // Log functionConstVar
// console.log(blockConstVar); // Error: blockConstVar is not defined outside the block
console.log(globalVarVar); // Access globalVarVar from function
console.log(functionVarVar); // Access functionVarVar from function
console.log(blockVarVar); // Access blockVarVar from function
}
exampleFunction();

Output:
Variable-Declaration
Frequently Asked Questions

Still have a question?

Let's talk

The global scope is the default scope where variables and functions are accessible throughout the entire script or application unless overridden. Learn more in our JavaScript global scope free course video.

Declare a variable outside any function using var, let, or const. However, var variables are automatically added to the global object (like window in browsers).
Example:

var globalVar = “I’m global”; 

Explore this topic in the JS global scope with free video tutorial.

Polluting the global scope increases the risk of naming conflicts and unexpected behaviors, especially in larger projects or when using third-party libraries. Discover best practices in the Free JavaScript global scope tutorial for beginners

Use IIFE (Immediately Invoked Function Expressions), modules, or namespaces to encapsulate variables.
Example:

(function() { 

  let localVar = “I’m local”; 

})(); 

Learn step-by-step in the JavaScript global scope with free tutorial.

The window object is the global object in browsers. All globally declared variables and functions using var are added to it. Learn more in the JavaScript global scope free course video.

Yes, global variables are accessible from any function unless shadowed by local variables with the same name. Watch this demonstrated in the JS global scope with free video tutorial.

The variable becomes global automatically (in non-strict mode), which is considered bad practice. Learn the impact of this in the Free JavaScript global scope tutorial for beginners.

  • Global Scope: Variables are accessible everywhere.
  • Local Scope: Variables are confined to a specific function or block.
    Discover their differences in the JavaScript global scope with free tutorial.

In strict mode, undeclared variables (when var, let, or const are omitted) throw an error instead of being implicitly global. Watch practical examples in the JavaScript global scope free course video.

  • Avoid declaring variables in the global scope.
  • Use let and const instead of var to prevent global leaks.
  • Encapsulate your code in functions or modules.
    Check out these tips in the JS global scope with free video tutorial.