Code highlights logo

Learn

Scope

Global Scope

Global scope refers to the accessibility or visibility of a variable or function throughout an entire program. Variables and functions defined in the global scope can be accessed from any part of the program, including within blocks, functions, or other scopes.

Defining Global Variables

A variable can be defined in the global scope by declaring it outside of any function or by omitting the var, let, or const keyword inside a function.

1// Global variable defined outside of any function
2var globalVar = 'I am global!';
3
4function exampleFunction() {
5 globalVarWithoutKeyword = 'I am also global!'; // Becomes global because no keyword is used
6}

Accessing Global Variables

Global variables can be accessed from any part of the code, including inside functions.

1function printGlobalVar() {
2 console.log(globalVar); // Outputs: 'I am global!'
3}

Modifying Global Variables

Global variables can be modified from anywhere in the code, which can lead to unexpected behavior.

1function modifyGlobalVar() {
2 globalVar = 'I have been modified!';
3}

Instructions

1.

Declare a new variable y within the printValue function, assign it the value of 20.

2.

Console.log the variable y within the printValue function.

3.

Outside the printValue function, try to console.log the variable y.

Sign up to start coding

Already have an account?

Sign In

Course content