Global scope is an important concept in JavaScript. It means that a variable can be accessed from different parts of the program. When we declare a variable outside a function or block, it can usually be accessed from other parts of the program.
For example:
let name = "Abishek";
function greet() {
console.log(name);
}
greet();
console.log(name);
Output:
Abishek
Abishek
Here, name is declared outside the function, so it can be accessed both inside and outside the function. This is called a global variable.
We can also create a global variable using const.
const country = "India";
function showCountry() {
console.log(country);
}
showCountry();
Output:
India
The country variable is declared outside the function, so the function can access it.
Global variables can also be changed when we use let.
let score = 100;
function changeScore() {
score = 50;
}
changeScore();
console.log(score);
Output:
50
Here, score initially has the value 100. When changeScore() is called, the value is changed to 50. This happens because score is a global variable and let allows its value to be reassigned.
But if we use const, the value cannot be reassigned.
const score = 100;
score = 50;
Output:
TypeError: Assignment to constant variable.
Global variables are useful when the same value needs to be used in different parts of a program. However, using too many global variables is not recommended because they can be accidentally changed and may cause bugs.
In simple words, global scope means a variable can be accessed from different parts of a JavaScript program. We should use global variables carefully and use local variables whenever possible.
Top comments (0)