- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to use Global Variables in JavaScript?
In this article, we are going to explore global variables and how to use them in JavaScript. But before moving on to using them, let’s see how to declare a variable.
A variable can be either declared as a global variable or a local variable. Each variable has a scope associated with it where it can be used. We can declare a variable by using varvar, let , and const keywords. Before ES6 only the var keyword can be used for declaration.
Global variables have a global scope and can be accessed from anywhere in the program or application. These variables are declared in the main body of the source code and outside all the functions. These variables are allowed to be used by every function.
Global variables are declared at the start of the block (top 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.
Example 1
In the below example, we will declare a global variable and see if it can be accessed by different functions or not.
# index.html
<!DOCTYPE html> <html> <body> <center> <h1 style="color: red;"> Welcome To Tutorials Point </h1> <h4 id="student1"></h4> <h4 id="student2"></h4> <script> var fname = "Steve"; // Declaring global variable outside the function myFunction(); // Global variable accessed from // Within a function function myFunction() { document.getElementById("student1").innerHTML = "First Name: " + fname; } // Changing value of global // Variable from outside of function document.getElementById("student2").innerHTML = "Full Name: "+ fname + " Jobs"; </script> </center> </body> </html>
Output
The above program will produce the following output.
Example 2
In the below example we declare a global variable using a window object inside a function and try to access this variable from within another function.
# index.html
<html> <head> <title>Global Variables</title> </head> <body> <h1 style="color: red;"> Welcome To Tutorials Point </h1> <p id="employee"></p> <script> function a(){ // Declaring global variable using window object window.salary=60000; } function b(){ // Accessing global variable from other function document.getElementById("employee").innerHTML ="Salary:"+window.salary } a(); b(); </script> </body> </html>
Output
It will produce the following output.