Skip to content

Scope of variables in JavaScript | Simple example code

  • by

Scope of variables in JavaScript only has two types Global Variables and Local Variables.

Note: In JavaScript, objects and functions are also variables.

Scope of variables in JavaScript and Examples

Let’s see HTML example code for both type of scope and understand the use and different of it.

Global Scope

A variables are outside of a function is considered a global scope variable.

“a” variable is a global variable.

<!DOCTYPE html>
<html>

<body>
	<script type="text/javascript">

		let a = "Hello";

		function msg () {
			console.log(a);
		}

		msg(); 
	</script>
</body>
</html>

Output:

Global Scope of variables in JavaScript

Note: If a variable is used without declaring it, that variable automatically becomes a global variable.

function msg() {
    a = "Hello"
}

msg();

console.log(a);

Local Scope

A local variable will be visible only within a function where it is defined. Local variables have Function scope: They can only be accessed from within the function.

“b” variable is a local variable.

<!DOCTYPE html>
<html>

<body>
	<script type="text/javascript">

		let a = "Hello";

		function msg() {
			let b = " World"
			console.log(a + b);
		}

		msg();
		console.log(a + b); 
	</script>
</body>
</html>

Output: Trying accessing local varible from the outside function will throw an error:- Uncaught ReferenceError: b is not defined

Local Scope of variables in JavaScript Example

Do comment if you have any doubts and suggestions on this basic JavaScript topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading