
317 views
JavaScript Global Variable
The global variable is a variable declared outside of any function, which means it is accessible from anywhere within the code. Global variables can be accessed and modified by any part of the code, including functions and other blocks.
Here is an example of declaring and using a global variable in JavaScript:
JavaScript
var globalVar = "Hello, world!"; // declaring a global variable
function sayHello() {
console.log(globalVar); // accessing the global variable within a function
}
sayHello(); // output: "Hello, world!"
In this example, the variable globalVar
is declared outside of any function, making it a global variable. The sayHello
function can access and print the value of globalVar
using the console.log
statement. When sayHello
is called, it outputs the value of globalVar
.