Functions and subroutines are basically smaller pieces of your script. They are generally a part that completed a specific task in the script and are very helpful in accomplishing the following:
- Creating reusable code to use in other scripts without having to re-write the code
- Making your code more readable
- Helpful in debugging a script and disabling a section of code
Functions and subroutines are VERY similar. They both offer a way to better organize your code into bite sized chunks, create re-usable sections that are easier to manage and modify, and they both preform a very specific task.
But, there is only one major difference in the two of them: a subroutine does it’s work and deals with it’s result inside itself without communicating the end result back to the routine that called it to run; a function on the other hand will communicate back to the calling routine some value such as the result of some calculation or an error condition for the calling routine to process and deal with in a manner that is fitting for the situation.
The following example code shows you how to write a subroutine and a function to add two numbers together:
Sub Add(Value1, Value2)
Dim Sum
Sum = value1 + Value2
WScript.Echo Value1 & ” + ” & Value2 & ” = ” & Sum
End Sub
Function Add(Value1, Value2)
Dim Sum
Sum = value1 + Value2
Add = Sum
End Function