What Is The Use Of Global Variables In JavaScript

admin_img Posted By Bajarangi soft , Posted On 25-09-2020

In JavaScript When you declared variable outside of a functions its called global variable .A JavaScript global variable is declared outside the function or declared with window object. It can be accessed from any function.So today we are going to discuss about global variable.

What Is The Use Of  Global Variables In JavaScript

Declare value variable and assign with 50 now this value variable can be used to any number of function.

For Example(1)
 
<button class="btn btn-primary" onclick="Function_a()">Click it</button>
<button class="btn btn-primary" onclick="Function_b()">Click it</button>
<script>
    var value=50;//global variable
    function Function_a(){
        alert("Am from A function "+value);
    }
    function Function_b(){
        alert("Am from B function "+value);
    }
</script>
 


Declaring JavaScript global variable within function

To declare JavaScript global variables inside function, you need to use window object. For example:

window.value=50;  


Now it can be declared inside any function and can be accessed from any function. For example:

function Function_a(){
    window.value=100;//declaring global variable by window object  
}
function Function_b(){
    alert(window.value);//accessing global variable from other function  
}
 


Internals of global variable in JavaScript

When you declare a variable outside the function, it is added in the window object internally. You can access it through window object also.
For example:

var value=50;
function a(){
    alert(window.value);//accessing global variable
}
 


Complete code for global variable in java script

<!DOCTYPE html>
<html>
<head>
    <title>Global Variables In JavaScript</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
</head>
<style>
   h2{
       color:red;
   }
</style>
<body>
<div class="container">
    <br>
    <br>
    <div class="text-center">
        <h1>Global Variables In JavaScript</h1>
    </div>
    <br>
    <div class="well">
        <button class="btn btn-primary" onclick="Function_a()">Am function A</button>
        <br>
        <br>
        <button class="btn btn-primary" onclick="Function_b()">Am function B</button>
    </div>
    <br>
</div>
</body>
</html>
<script>
    var value=50;//global variable
    function Function_a(){
        alert("Am from A function "+value);
    }
    function Function_b(){
        alert("Am from B function "+value);
    }
</script>

 

Related Post