Table of Contents
Back Button
Back to Chapter
Control Statements
No items found.
Function & Events
No items found.
Array and its Types
No items found.
OOP : Object Oriented Programming
No items found.
Javascript Standards
No items found.
HTML DOM
No items found.
Javascript : Advanced 1
No items found.
Javascript : Advanced 2
No items found.
Additional JavaScript
No items found.

Scope

Scope is defined as the availability of variables in other parts of the code.

Types of Scope

In JavaScript, a variable has two types of scope:

  1. Global Scope
  2. Local Scope

We are not discussing about Let, because it has block scope. We have discussed about in

Global Scope

Any Variable that can be used in all parts of the code is called Global Scope Variable.

Syntax

var variableName; function functionName(parameters){ //variableName can be used here. } //variableName can be used here.

Example

var welcomeText = "Hello World"; function welcomeUser(){ console.log(welcomeText); } console.log(welcomeText); //output //Hello World //Hello World

Here,

We have declared a variable welcomeText, it is declared outside the function that is why it can be accessed anywhere in the Program.

Local Scope

Any Variable that can be used only inside the function, in which it is declared is called Local Scope Variable.

Syntax

function functionName(parameters){ var variableName; //variableName can be used here. } //variableName can not be used here.

Example

function welcomeUser(){ var welcomeText = "Hello World"; console.log(welcomeText); } console.log(welcomeText); // This will give an error. //output //Hello World

Here,

We have declared a variable welcomeText, it is declared inside the function that is why it can be accessed only inside the function. When we try to use it outside the Function, it will give an Error.

Conclusion

  • Global Scope is Accessible Throughout the Program.
  • Local Scope is Accessible only inside the Function in which it is defined.
  • Block Scope Variable let is only Accessible inside the {} parenthesis in which it is defined.

Ask queries
Contact Us on Whatsapp
Hi, How Can We Help You?