DEV Community

Sourav Bandyopadhyay
Sourav Bandyopadhyay

Posted on

What is Global variables in javascript?

In JavaScript, a global variable is a variable that is accessible from anywhere in the code, including inside functions and blocks.

Global variables are declared outside of any function or block, usually at the top of a script. Once declared, they can be accessed and modified from any part of the code, which makes them convenient but also potentially risky, as they can be accidentally overwritten or modified by different parts of the code.

Here's an example of how to declare a global variable in JavaScript:

var globalVariable = "I am a global variable";

console.log(globalVariable)

function myFunction() {
  globalVariable = "I am modified";
  console.log(globalVariable);
}

myFunction(); // outputs "I am modified"
console.log(globalVariable); // also outputs "I am modified"

Enter fullscreen mode Exit fullscreen mode

In this example, globalVariable is a global variable that can be accessed and modified from any part of the code.

It's important to be careful when using global variables in JavaScript, as they can make code harder to maintain and test. It's usually better to use local variables when possible, and pass values between functions using parameters and return values.

Top comments (0)