A global variable in JavaScript is a variable that is declared outside of any function and can be accessed from anywhere in the code. These variables are stored in the global scope, which means they are available throughout the entire program, including inside functions.
var name = "John Doe";
function sayHello() {
console.log("Hello " + name);
}
sayHello(); // Output: Hello John Doe
In the example, the variable name is declared outside of the sayHello function and is accessible within the function.
It’s important to be mindful of the use of global variables because they can have unintended consequences, such as conflicts with other variables with the same name, or unexpected changes to the value of a global variable from any part of the code. To avoid these issues, it’s best to limit the use of global variables and instead use local variables, which are declared within functions and have a more limited scope.
In JavaScript, you can access global variables using the window object. The window object is the global object in the browser and represents the browser window. Any variable declared in the global scope becomes a property of the window object.
For example, consider the following global variable:
var name = "John Doe";
You can access the name variable using the window object like this:
console.log(window.name); // Output: John Doe
It’s also possible to access the variable directly, without using the window object:
console.log(name); // Output: John Doe
In both cases, you get the same result because the name variable is in the global scope and is accessible anywhere in the code. However, using the window object to access global variables is useful in cases where you need to be explicit about the scope or when you’re not sure if a variable is in the global scope or not.