DEV Community

ABISHEK M
ABISHEK M

Posted on

Global Scope in JavaScript

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);
Enter fullscreen mode Exit fullscreen mode

Output:

Abishek
Abishek
Enter fullscreen mode Exit fullscreen mode

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();
Enter fullscreen mode Exit fullscreen mode

Output:

India
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

Output:

50
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

Output:

TypeError: Assignment to constant variable.
Enter fullscreen mode Exit fullscreen mode

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)