Declaring global variable in JavaScript Examples
Example 1: Declaring Global Variables in JavaScript
Here, globalVar1
, globalVar2
, globalVar3
, globalVar4
, PI
, and WEBSITE_NAME
are declared as global variables and can be accessed from anywhere within the script.
// Declaring global variables using var keyword
var globalVar1 = "Hello";
var globalVar2 = "World";
// Declaring global variables using let keyword
let globalVar3 = "JavaScript";
let globalVar4 = "Example";
// Declaring global variables using const keyword
const PI = 3.14;
const WEBSITE_NAME = "My Website";
// Accessing and printing global variables
console.log(globalVar1 + " " + globalVar2); // Output: Hello World
console.log(globalVar3 + " " + globalVar4); // Output: JavaScript Example
console.log("The value of PI is: " + PI); // Output: The value of PI is: 3.14
console.log("Website Name: " + WEBSITE_NAME); // Output: Website Name: My Website
Output
Hello World JavaScript Example The value of PI is: 3.14 Website Name: My Website
Example 2: Accessing and Modifying Global Variables in JavaScript
The code demonstrates accessing a global variable Marks
both within and outside a function. Initially set to 10
, it’s accessed inside myFunction()
. Later, it’s modified outside the function scope to 200
.
var Marks = 10;
// Declaring global variable outside the function
myFunction();
// Global variable accessed from
// Within a function
function myFunction() {
console.log("global value of Marks is: ", Marks);
}
// Changing value of global
// Variable from outside of function
{
Marks = 200;
console.log("local value of Marks is: ", Marks);
}
Output
global value of Marks is: 10 local value of Marks is: 200
Contact Us