One of the most useful methods for debugging VBA is Debug.Print, to see what variables contain or what a statement returns. JavaScript has a similar capability: console.log();.

As with Debug.Print, console.log(); accepts a String argument, which can integrate the values of variables, and prints it out to the console – usually a window in the JavaScript IDE you’re using. In Script Lab the console window is the bottom section of the “Run” pane.

The standard JavaScript way to concatenate static strings with variables is to use the + sign, as described in a very early post in the series.

The message in the screen capture to the right comes from the code sample in the previous post in this series. Using standard JS concatenation, the code would look like this:

console.log("The selected text was             
       " + range.text + 
       " formatted with the font "
       + + ", size "  
       + range.font.size + " and underlined with " 
       + range.font.underline + ".");

The code in the previous article, however, looks a bit different:

console.log(`The selected text was  "${range.text}" 
           formatted with the font "${}", 
           size "${range.font.size}" and
           underlined with "${range.font.underline}".`);

This version uses a concept called “template literals“, a syntax that was introduced in the ECMAScript (ES) standard in 2015.

The template literal is signalled by the use of the back-tick, also called accent-grave, character (`) at the beginning and end of the string. This is not an apostrophe.

The variable name is surrounded by quotes and curly braces, with a dollar sign preceding the opening curly brace. This construction is called a “placeholder”. Behind the scenes, the entire expression – text and placeholders – is passed to a function which returns the concatenated string. As far as the developer is concerned, this function is a “black box” – we don’t have to know anything about it.

Because this is new in ES6, template literals won’t work in all browsers if you try to use them in “normal” JavaScript. But they will always work in Office Web Add-ins since the host pane in the Office application is a version of the Microsoft browser that supports ES6.

More information on using the console object can be found in the documentation.

The next post in this series will be an overview of the “plumbing” in Script Lab.

Leave a Reply