Tech Study

JavaScript Variable Scope

Imagine there are two rooms, A and B, and you are in room A. Room A is in it and accessible from within it. So you fall under the A scope. However, for room B, you are outside the room and cannot be accessed from inside, so it is not part of the scope.

Similarly, the scope of a variable is the code block or area where the variable can be accessed. A variable’s scope indicates the visibility and accessibility of the variable in different parts of the program. Scope determines which parts of a program can access a variable and where it can be used.

Types of variable scope in JavaScript are as follow:

  • Global variable: 

Variables declared outside of a function are considered global and are accessible throughout the program.

Example:

var globalVari = "Global variable is";

function myFunction()

{

console.log(globalVari);

}

myFunction();

function anotherFunction()

{

console.log(globalVari + " a variable that is stated in the global scope in other words.");

}

anotherFunction();

Output:

Global variable is

Global variable is a variable that is stated in the global scope in other words.

  • Local variable: 

Variables declared within a function are considered local and can only be accessed within that function.

Example:

function myFunction() 

{

var localVari = "It is a local variable";

console. log(localVari);

}

myFunction(); 

console.log(localVari);

Output:

It is a local variable

Uncaught ReferenceError: localVariable is not defined

Java Final keyword

Introduction : java final keyword The final keyword present in Java programming language is generally used for restricting the user. …

Read more

C++ Memory Management: new and delete

C++ Memory Management We know that arrays store contiguous and the same type of memory blocks, so memory is allocated …

Read more