Summary: Some notes on variable scoping in VBScript.
In VBScript, the following code doesn't work, which I understand:
Option Explicit s = "Hello"
However, the following code works fine:
Option Explicit s = "Hello" Dim s
Why can we use a variable before declaring it in VBScript?
If you think that the above looks odd, do you think this looks normal?
Dim s s = Foo(123) Function Foo(x) Foo = x + 345 End Function
Here the function is being used before it is declared. Similarly, variables can be used before they are declared. The behaviour is by design. Variable declarations and functions are logically “hoisted” to the top of their scope in VBScript.
Also, declaring a variable twice in the same script block is illegal, but redefinition in another block is legal. Procedures may be redeclared at will except if the procedure is in a class, in which case redeclaration is illegal.
Did you know that this is legal in VBScript?
s = Foo(123) If Blah Then Function Foo(x) Foo = x + 345 End Function End If
This is not recommended, but it is legal.
Dim i For i = 1 To 2 Rhino.Print c Next Const c = 10
And this works:
For i = 1 To 2 Rhino.Print c Dim i Next Const c = 10
But, this fails with a “name redefined” error:
For i = 1 To 2 Rhino.Print c Const c = 10 Dim i Next