Wednesday, April 23, 2025

JavaScript Global vs Local Variables

Global variables are those that are declared outside of any function and are accessible throughout the entire program, while local variables are those that are declared within a function and are only accessible within that function.

Global variables are often used to store information that needs to be accessed by multiple functions or throughout the entire program. However, excessive use of global variables can lead to potential issues, such as naming conflicts between different functions or unexpected changes to the value of the variable from unintended sources.

On the other hand, local variables are only accessible within the function they are declared in, making them more secure and less prone to naming conflicts. Local variables are typically used to store temporary values that are only needed within a specific function.

It's important to note that when a local variable and a global variable have the same name, the local variable takes precedence within the scope of the function. This is known as variable shadowing, where the local variable "shadows" the global variable of the same name. 


<!DOCTYPE html>
<html>
<head>
<!-- <script src="main.js"></script> -->
</head>
<body>

<script>

	var number = 456;
	
	function printing() {
		var number = 777;
		
		document.write("Local Variable: " + number);
		document.write("<br><br>");
	}
			
	printing();
	
	document.write("Global Variable: " + number);
		
</script>
	
</body>
</html>

In this script, there is a global variable named number with a value of 456. Then there is a function named printing() that defines a local variable with the same name number and assigns it a value of 777.

When the function is called, it will execute and print the value of the local variable number which is 777. After the function is executed, the script will continue to execute and print the value of the global variable number which is 456.

This demonstrates the concept of local vs. global variables. Local variables are defined within a function and are only accessible within that function, while global variables are defined outside of functions and are accessible throughout the entire script. If a local variable has the same name as a global variable, the local variable takes precedence within that function, while the global variable remains unchanged.

No comments:

Post a Comment

Tkinter Introduction - Top Widget, Method, Button

First, let's make shure that our tkinter module is working ok with simple  for loop that will spawn 5 instances of blank Tk window .  ...