VBScript Variable Scope



VBScript Variable Scope :

Scope of variable defines the visibility of the variable. Variables having following type of scopes –

Scope of Variable Description
Dim Visible at Procedure Level
Public Visible in all procedures
Private Visible in the script

1. DIM : Procedure Level

  1. When variable is declared using ‘Dim’ keyword at a Procedure level are available only within the same Procedure.
  2. When variable is declared using ‘Dim’ keyword at a Script level are available within the same script.
<!DOCTYPE html>
<html>
<body>
<script language="vbscript" type="text/vbscript">

Dim num1
Dim num2

Call sum()

Function sum()
   num1 = 100
   num2 = 200
   Dim res
   res = num1 + num2
   Msgbox res ' Displays 300
End Function

Msgbox num1   ' Displays 100 
Msgbox num2   ' Displays 200 
Msgbox res    ' res is not visible outside procedure

</script>
</body>
</html>

Explanation :

In the above example we have declared two variables at script level so that these two variablesa re visible in procedure as well.

Dim num1
Dim num2

These variables are also referred as global variables. Now we have declared variable ‘res’ at procedure level using DIM then it will not be visible outside the procedure.