Reputation: 7954
I noticed that I can Dim
a variable after using it or (in other words) use it before Dim
ing, even when using Option Explicit
. Try this:
Option Explicit
x = "before Dim"
WScript.Echo x
Dim x
x = "after Dim"
WScript.Echo x
The same works fine in a Sub
or Function
.
Apparently, it does not matter on which line the Dim
is, as long as it is in the same scope (current Function
/Sub
or global). I wonder why this works. Microsoft's documentation explicitly says (emphasis mine):
The lifetime of a script-level variable extends from the time it is declared until the time the script is finished running.
I read this like: first Dim
then use. But I was wrong...? Why is this?!
VB6 does not allow this:
---------------------------
Microsoft Visual Basic
---------------------------
Compile error:
Variable not defined
---------------------------
OK Help
---------------------------
Upvotes: 4
Views: 254
Reputation:
The extract is the contract and what you must follow because we don't take dependencies on implementation. For your general info declares are hoisted to the top. Eric Lippert wrote:
Why can we use a variable before declaring it in VBScript? ...
What's up with that? Well, let me ask you this -- if you think that looks weird, why do you think this looks normal?
Dim s s = Foo(123) Function Foo(x) Foo = x + 345 End Function
There the function is being used before it is declared, but that doesn't bug you, right?
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 both VBScript and JScript.
EDIT
VBScript follows VBA rules as far as possible. This is the implementation doc for implementing VBA. For VBS/VBA programmers it is for info only.
https://msdn.microsoft.com/en-us/library/dd361851.aspx
Upvotes: 9