Global scope means a place where variables can be seen and used anywhere in your whole program. It helps share information across different parts of your code.
0
0
Global scope in Javascript
Introduction
When you want to keep a value that many parts of your program need to use.
When you want to store settings or options that affect the whole program.
When you want to share data between different functions or files.
When you want to keep track of something that lasts while the program runs.
When you want to create simple examples or quick tests without complex structure.
Syntax
Javascript
let myGlobal = 10; function show() { console.log(myGlobal); } show();
Variables declared outside any function or block are in the global scope.
Global variables can be accessed from anywhere in the code.
Examples
This variable is global because it is outside any function.
Javascript
let greeting = 'Hello'; console.log(greeting);
Variable
count is global and used inside the function.Javascript
var count = 5; function printCount() { console.log(count); } printCount();
Constant
PI is global and used in the function.Javascript
const PI = 3.14; function area(r) { return PI * r * r; } console.log(area(2));
Sample Program
This program shows a global variable message used inside a function and outside it.
Javascript
let message = 'Good morning!'; function greet() { console.log(message); } greet(); console.log(message);
OutputSuccess
Important Notes
Be careful with global variables because too many can make your program confusing.
Use global scope only when you really need to share data everywhere.
Modern JavaScript modules help avoid unwanted global variables.
Summary
Global scope means variables are available everywhere in your code.
Declare variables outside functions to make them global.
Use global variables carefully to keep your code clear and easy to understand.