Scope of variables in JavaScript | Simple example code

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.

Output:

Global Scope of variables in JavaScript

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

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.

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: All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.