/  Technology   /  What are global variables –  How are these variable declared and what are the problems associated with using them?
global

What are global variables –  How are these variable declared and what are the problems associated with using them?

 

The variables that can be accessed from any place in the program are known as global variables. These are the variables declared in the main body of the source code as well as outside of all methods. These variables are accessible to all functions. The var keyword is used to declare variables at the global level.

What are global variables?

Global variables are most beneficial when all functions require access to the same data.

The global variable exists until the program runs.

<body>
    <script>
        var num1 = 9;// Here a declared num1 variable with var keyword globally
        console.log(num1);// number
    </script>
    <script>
        var num1 = 20;// Here we  redeclared num1 variiable with var keyword
        console.log(num1);// number
    </script>
    <script>
        console.log(num1);// Here we  accessing global variable (num1). 
        //We can access the a globally declared variable anywhere in the function.
        //The main disadvantage for Global variables are if we reassign same variable with another value,
        // It accepts newly assigned value. Means Overwrites previous value.
        //Global variables are used many places in the program. If we modified in one place
         // it effects everywhere in the program.
    </script>
</body>

Console.log:

gobal

How Global variable declared?

We can declare variables by using the var keyword.

<script>
    var num1=9;// Here a declared num1 variable with var keyword globally
    console.log(num1);// number
</script>

<script>
    var num1=20;// Here we  redeclared num1 variable with var keyword
    console.log(num1);// number
</script>

What are the problems associated with using them?

The issue with global variables is that because every function has access to them, it becomes progressively difficult to determine which functions actually read and write them. To understand how the program works, you must consider every function that alters the global state.

 

Leave a comment