VBA->JS: Named functions (Syntax & Concept)

Now that you have an idea of the basic JavaScript syntax it’s time to expand from code snippets to more complex subjects, starting with functions. This topic will extend over a number of posts as it’s not quite as simple as what we know from VBA…

Functions perform the same service in JavaScript as in VBA: it’s a way to re-use code so that you don’t have to type it out each time the functionality is required.

In the VBA editor we’re accustomed to inserting a page for code – usually a “module”, declaring any options, as well as global and module level variables at the top, followed by a number of procedures of type “sub” or “function”. The main difference between these last two is that a function may return something to the line of code that calls it.

JavaScript does not have the concept of “sub” procedures, only functions. And since the code is part of web page there are no “modules” and the calling line of code does not have to be within another procedure. The syntax is a bit different from that of VBA (as usual), but the basic logic is the same:

VBA JS
Function Simple() As String
    Simple = "result"
End Function

Sub TestFunction()
    Debug.Print Simple
End Sub
function Simple() {
  return "result"
}
 
Simple();

If you’ve been following along, you recognize the curly braces defining the function’s code block, the fact that there’s no semicolon in the line with the function declaration, but there is a semicolon at the end of the code line(s) within the function code block.

As with variables, there’s no way to assign a data type to a function, so there’s no equivalent to As String on the JS side.

New is the use of the keyword return. JavaScript uses this instead of assigning a value to the function name at the end of the code block. It’s important to note that at this point execution returns from the function back to the caller: even if code would follow this line, it would not be executed.

Another important point is that you need to call a function using parentheses: Simple();. If you forget the parentheses JavaScript returns the name of the function and does not execute the function. So the line Simple; would return the string: Simple.

As with VBA, you can pass parameters to a function in JavaScript:

VBA JS
Function ConcatStrings( _
         str1 As String, str2 As String) _
         As String
    ConcatStrings = str1 & vbTab & str2
End Function

Sub TestFunction()
    Debug.Print ConcatStrings("one", "two")
End Sub
function ConcatStrings(str1, str2) {
  return str1 + "\t" + str2
}
 
 
 
ConcatStrings("one", "two");

Here, again, data types cannot be assigned to the parameters.

JavaScript doesn’t care if you pass more parameters to the function than are defined; you won’t get a “Wrong number of arguments or invalid property assignment” notification from the compiler. Excess arguments are simply ignored. The line of code ConcatStrings("one", "two", "three"); returns the same result: “one two”.

You can also pass fewer than the declared number of parameters without needing to declare any as Optional as you would in VBA. So rather than getting the error “Argument not optional” if ConcatStrings("one"); is used you get back: “one undefined”. Notice that the function still works with the parameter str2 – it has the default value undefined that JavaScript converts to a string for purposes of the concatenation.

So, is there a way to pass an undefined number of parameters to a function? Yes – JavaScript stores all paremeters passed to a function in an array that can be accessed by the built-in object arguments:

function ConcatStrings() {
  var returnString = "no params";
  if (arguments.length > 0) {
   returnString = arguments[0];
  }
  for (var i=1; i < arguments.length; i++) {
      returnString += "\t" + arguments[i];
  }
  return returnString; 
}
 
ConcatStrings("one", "two", "three", "four");
//Result: "one two three four"

The built-in array property length returns the number of members the array contains. The example tests whether the array contains any members at all (> 0). If that is the case, the first parameter’s value is assigned to the string that will be returned. In a for loop the remaining members’ values are concatenated to returnString. If the function were called using ConcatStrings(); “no params” would be returned.

JavaScript comes with a number of useful built-in functions. This site has a complete list, but no examples. If you search the Internet you’ll find pages with examples, but none turned up in my search with a complete list and examples.

The next post will discuss the basics of using objects, including how to associate a function with an object.



One Response to “VBA->JS: Named functions (Syntax & Concept)”

  1.   Felipe Costa Gualberto Says:

    There’s an extra after result ; in the example below, it should be removed. The correct version would be:

    function Simple() {
    return “result”
    }
    Simple();

Leave a Reply