Friday, September 30, 2022
Home Integration/Interfaces JavaScript Fundamentals for Mirth Developers

JavaScript Fundamentals for Mirth Developers


  • Familiarity with programming syntax
  • Familiarity with programming terminology
  • Mirth Connect basics
  • Basic knowledge of HL7

Mirth developers must focus on two major areas to be successful – knowledge of healthcare/standards and technical skills. If you are coming from more of a clinical background then learning JavaScript basics is a great place to start. Now, if you are just starting out with Mirth, what are the fundamental JavaScript concepts that you need to know?

Before diving in, it’s worth noting that JavaScript programming in Mirth is very different than writing JavaScript for front-end web development. For example, you won’t be accessing the DOM (Document Object Model) or specific web elements to manipulate. Rather, newer Mirth developers should focus on programming concepts and becoming familiar with Mirth-specific JavaScript syntax.

Furthermore, keep in mind that you can include Java code in your channels. When you see Java code in channels, it’s usually in the form of a method (function) call – more on this later. However, this article will primarily focus on JavaScript programming fundamentals.

JavaScript Variables and Data Types

JavaScript is an object-oriented language that has all the standard data types plus some unique to JavaScript. These data types include:

  • Number
  • Text
  • Boolean
  • Null
  • Undefined

Other programming languages will make further distinctions for different types of numbers; however, JavaScript keeps it pretty simple with the above types.

The number data type is any numerical value with or without a decimal point. All the examples below are examples of JavaScript numbers.

var x = 1;
var temp = 98.6;
var num = -3.14;

The text data type is any single character or a string of characters. Below are examples of text in JavaScript.

var unit = "mmHg";
var facility = 'My Clinic';

Notice that you can use either the single or double quotes to define a string literal in JavaScript. This is great because this is not always the case in some other languages. For example, in Java, you must use double quotes when forming a String literal.

A Boolean is an expression that either evaluates to true or false. Look at the following example.

var isInPatient = true;
var isDeceased = false;
var isOutPatient = !isInPatient;

True and false are reserved keywords in JavaScript. That is, you can assign true or false to any variable directly.

Furthermore, you can use the exclamation point (not operator) to negate the boolean value. For example, the not operator would turn a true into false. This means that the value of isOutPatient is false.

Next, developers can use the AND and OR operators when constructing conditions. AND and OR are denoted by a double ampersand and double pipe, respectively. Consider the following example.

var isSingle = true;
var isWidowed = false;
var isDivorced = false;
var isMarried = !(isSingle || isWidowed || isDivorced);
var isSingleAndWidowed = isSingle && isWidowed;

When isMarried is evaluated, it checks if isSingle is true or if isWidowed is true or if isDivorced is true. If any one of these is true then isMarried is false because of the not operator around the entire expression. This is also a good example of effectively using parentheses with boolean expressions. Similarly, isSingleAndWidowed is only true if isSingle and isWidowed are both true. In any other scenario, isSingleAndWidowed will be false.

When programming in JavaScript, you also need to understand null and undefined. For a variable to be null, you have to assign it null. However, for a variable to be undefined, by definition, means that it was never assigned any value. Take the following example.

var myNull = null;
var myUndefined;

If you were to reference myNull and myUndefined they would contain null and undefined, respectively. This is important to know when checking for null and undefined variables.

Furthermore, JavaScript is not a strongly typed language. This means that developers don’t explicitly specify what type of data is going into the variable. This is accomplished using the var keyword.

var myVariable = "I love Healthcare Information Technology!";

Using var is preferred with Mirth since you could be pointing your variables at Java objects or any other data type for that matter. This is the flexibility of using a language like JavaScript. Note that the semicolon at the end of a JavaScript statement is optional. In some languages, a semicolon is required so it’s not a bad habit to get into.

JavaScript Loops

Loops are repetitive programming structures that every Mirth developer needs to master. Developers can use loops to execute the same block of code over and over again depending on different criteria.

JavaScript has three different loops that you can utilize. These include:

  • While
  • For
  • For-in


A while loop runs while a provided condition is true. Once this condition is no longer true, program execution will exit the loop. For example:

var name = msg['PID']['PID.5'];
var result = "";
var i = 0;
while(i < name.length()) {
   result = result + " " + name['PID.5.' + i];
   i = i + 2;

The above loop will concatenate every other component of field PID.5 into a variable named result.


A for loop is typically used when the developer wants a loop to run a set number of times regardless of a condition. The condition is instead used to determine when to exit the loop. Take the following example.

var name = msg['PID']['PID.5'];
var result = "";
for(var i = 0; i < name.length(); i++) {
   result = result + " " + name['PID.5.' + i];

The only difference between the above code and the previous example is that this one is concatenating every component of PID.5 instead of every other component.

Inside the parentheses, the for loop has three parts. First, developers must declare the variable used for iteration, which is i in this example. Next is the condition that typically involves the variable used for iteration; however, JavaScript does not necessarily require this.

The last part describes how you want to iterate your variable. The following piece of code increments i by one for each iteration.


If you wanted to increment i‘s value by two each iteration then you could use the following JavaScript statement.

i = i + 2;


A for-in loop (also called a for-each loop) is exactly like a for loop except that it is less flexible. With for-in, you must visit every item in the object that you are iterating over. With a for loop, you could, for example, only iterate over the even elements of an array. However, this is not possible with a for-in loop. To understand this concept better, take the following example.

for each (field in msg.MSH.children()) {'child '+ i +': ' + field.toString());

The above for-in loop iterates over all fields in the MSH segment and writes a log message for each child. Again, with this for-in loop, you must visit every field in the MSH segment.

JavaScript Conditions

A condition in programming is like a fork in the road for a program in execution. Meaning, the program can go either left, right, or in another direction depending on certain criteria. There are two main types of conditional structures in JavaScript:

  • If Statements
  • Switch Statements

If Statements

If statements use the keywords if, else, and else if to tell a program which block of code to execute. Take the following example of a simple if-else statement.

var obsID = msg['OBX']['OBX.3']['OBX.3.1'];
if(obsID == "HEIGHT") {
} else {

The piece of code above first grabs the observation ID from OBX.3. The program will then evaluate obsID. If obsID has a value of ‘HEIGHT’ then the program will execute the function doThis(). If obsID has any other value than ‘HEIGHT’ then the program will execute the function doThat().

In the if-else scenario, the program can only go one of two ways with else being the default block if the condition is not satisfied. Don’t worry if you are unfamiliar with functions at the moment as they will be discussed in the next section.

Next, consider the following example that uses else-if and else clauses.

var obsID = msg['OBX']['OBX.3']['OBX.3.1'];
if(obsID == "HEIGHT") {
} else if(obsID == "WEIGHT") {
} else {

The only difference between this example and the previous one is that there are three options instead of two. First, the program will check to see if obsID contains a value of “HEIGHT”. If this is true, then the program executes the function doThis(). If it’s false, then the program will continue down and check every else-if afterward until it finds a match.

The else clause at the end is optional but it functions the same as in the previous example. If none of the else-ifs evaluate to true, then doNothing() gets executed.

Switch Statements

Switch statements use the keywords switch and case to tell a program which block of code to execute. Consider a familiar example using a switch statement.

var obsID = msg['OBX']['OBX.3']['OBX.3.1'];
switch (obsID) {
   case "HEIGHT":
   case "WEIGHT":

A switch statement compares an expression (obsID in this case) to the values in the case clauses. If the program finds a match then it will execute the block of code associated with that case clause.

In this case, if obsID has a value of ‘HEIGHT’ then the program will execute doThis(). If obsID has a value of ‘WEIGHT’ then the program will execute doThat(). If obsID does not equal either of these values then it will execute the block of code in the default clause, which is doNothing() in this case.

Finally, keep in mind that Mirth developers can use an indefinite number of case clauses just as they can use an indefinite number of if-else statements.

JavaScript Functions

In programming, a function is a block of code that is referenced by an identifier when that code needs to be executed. Functions exist so that programmers can reuse the same code over and over again.

If there is an action that needs to be performed over and over again, it’s better to just put that block of code into a function and use the function rather than repeatedly typing the same code again and again.

The structure of a function is as follows:

function myFunctionName(paramOne, paramTwo, paramThree) {
  var result = null;
  // Do some work here on result
  return result;

Start with the function keyword followed by your function name. After the function name, you will see the function’s parameters. Parameters are the inputs to a function. Functions often return an output based on these inputs. Also, a function can have any number of parameters. This is why you see a return statement at the end of the code block. However, JavaScript functions do not have to return anything. The function can simply do some other work without provided an output.

Mirth developers will need to know how to effectively use functions as well as create functions for their channels. If a function already exists, developers need not waste any time re-inventing the wheel. However, if something doesn’t exist, Mirth developers need the ability to create it.

Using Functions

Mirth has a plethora of available functions for developers to use in their channels. While this article is not intended to detail every Mirth Connect function, here are a couple of examples.

// Read a file of messages and map it to the Channel Map
var filePath = "C:/Temp/MyMessages.hl7";
var file =;

// Get the channel name from the channel ID
var channelID = "1234567";
var channelName = ChannelUtil.getChannelName(channelID);
channelMap.put('My Channel Name',channelName);

The read function looks at the file at the specified file path, which is passed in through the parameter, and then returns the file using the default charset encoding.

Similarly, the getChannelName function returns the channel name based on the channel ID that is passed in.

Both of the functions used above come from Mirth User API (Application Programming Interface). You can find the entire User API for Mirth 3.10.1 here. Note that these are Java functions, not JavaScript functions. However, you can utilize them within your scripts like any other function.

Creating Functions

Mirth developers must create functions to use in their channels when necessary. However, creating functions requires developers to think algorithmically and in terms of inputs and outputs.

What output should this work produce? What are the input(s) needed to accomplish this work? Are inputs even necessary? How should my function turn inputs into outputs?

These are all questions that you must answer in order to write an effective function. Also, make sure to pick good names for your function, parameters, and variables that you define.

You can use the function outline at the beginning of this section as a starting point for all your functions.

JavaScript Arrays

An array is a data structure used to store one or more values using a single variable. You can think of arrays as a simple list or multi-dimensional grid in some cases. For example, you can create an array where each element is an array. We could refer to this as a two-dimensional array. However, you can create arrays with more than two dimensions if need be.

Now, consider the following example.

var msh1 = msg['MSH']['MSH.1']['MSH.1.1'];
var msh2 = msg['MSH']['MSH.2']['MSH.2.1'];
var msh3 = msg['MSH']['MSH.3']['MSH.3.1'];

var MSHArray = [msh1,ms2,msh3];


MSHArray contains msh1, msh2, and msh3. Additionally, developers can reference any element of an array using the square bracket notation. MSHArray[0] gets the first element in the array. MSHArray[1] gets the second element in the array. MSHArray[2] gets the third element in the array.

This notation is called array indexing. The number inside square brackets is called the index. This comes into play often when you are looping through different parts of a message, for example.

for(var i = 0; i < msg['OBX'].length(); i++) {
   if(i > 0) {
      delete msg['OBX'][i];

The above code deletes every OBX segment in the message except for the first OBX. msg[‘OBX’] contains all the OBXs in the message but developers can use array notation to reference any single OBX from the message. This is a great example of how arrays and loops work together to do the heavy lifting for Mirth developers.

JavaScript Objects

JavaScript objects are data structures that developers define themselves. Objects can represent anything. In the context of Healthcare, this could be a patient panel, a vital sign, facility, etc. Here is an example of a JavaScript object.

var facility = {
   "name" : "County Hospital",
   "address" :  {
                   "street" : "123 Main Street",
                   "city" : "Gothom",
                   "state" : "XX"
   "phone" : "XXX-XXX-XXXX"

Objects contain a series of properties. Each property has a name and value. For example, “name” would be the name of property and “County Hospital” would be the value. These properties can be of any data type. Notice that facility also has an object, address, as one of its properties.

Accessing Object Properties

Mirth developers can easily access an object’s property using one of the following notations.

var address = facility["address"];
var phone =;

Again, address will now point to its object containing street, city, and state, and phone will contain ‘XXX-XXX-XXXX’.

While this section is not a comprehensive guide to JavaScript objects, there will be times where creating JavaScript objects could be advantageous for you, which is why you should be aware of how objects work in JavaScript.


Why You Must Learn Mirth Connect’s User API Now

Prerequisites Basic knowledge of Mirth ConnectBasic knowledge of JavaScriptBasic knowledge of software documentation and APIsBasic knowledge of Java development NextGen provides several different APIs (Application Programming...

Leverage Mirth’s Channel Scripts Now

Prerequisites Basic knowledge of Mirth ConnectBasic knowledge of JavaScript Each Mirth Connect channel gives you the ability to leverage four different scripts that have different triggers,...

Reference a Custom Jar File in Mirth Connect Now

Prerequisites Knowledge of Java developmentKnowledge of Eclipse or another Java IDEKnowledge of Mirth Connect Many Mirth professionals are unaware that they can write their own custom...

Most Popular

Mirth Connect Extensions: What You Need to Know

Prerequisistes Basic Knowledge of Mirth Connect Overview Users can navigate to Mirth Connect's Extensions screen by selecting Extensions on the left-hand side. You should now see the following...

Take a Tour of System Settings in Mirth Connect Now

Prerequisites Basic Knowledge of Mirth Connect Introduction Mirth Connect has a multitude of system settings that are available for configuration. In larger companies, there will often be...

Why You Must Master Mirth’s Message Template Tool Today

Prerequisuites Basic Knowledge of Mirth ConnectKnowledge of Programming in Mirth Connect Introduction When writing scripts in Mirth Connect, you have a message template tool that allows you...

Make Sense of HL7 v2 Messages Effortlessly Now

Prerequisites Beginner Knowledge of HL7 Introduction If you've been in Healthcare Information Technology for any period of time, you have definitely heard of HL7 (Health Level 7)....

Recent Comments