Open In App

How to declare Global Variables in JavaScript ?

Last Updated : 18 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Global Variables

Global variables in JavaScript are variables declared outside of any function. These variables are accessible from anywhere within the script, including inside functions.

  • Global variables are declared at the start of the block(top of the program)
  • Var keyword is used to declare variables globally.
  • Global variables can be accessed from any part of the program.

Note: If you assign a value to a variable and forgot to declare that variable, it will automatically be considered a global variable.

How to declare Global Variables in JavaScript?

In JavaScript, you can declare global variables by simply declaring them outside of any function or block scope. Variables declared in this way are accessible from anywhere within the script.

Here’s how you declare global variables:

// Declare global variables outside of any function or block scope
var globalVar1 = "Hello";
let globalVar2 = "World";
const globalVar3 = "!";

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.

JavaScript
// 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.

Javascript
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



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads