JavaScript Automatic semicolon insertion in case of return

Today I’m going describe something not directly related to ServiceNow. But JavaScript is our language and we use it almost every day. The issue I’m going to write about might be weird for you if you have some background in languages like Java or C#.

Let’s write some simple code:

function getObject(){
    return{
        param: 5
    }
}

var myObject = getObject();
gs.print(myObject.param);


And run it in Background Script:

As expected the output is 5.

But let’s make a small change: add new line after ‘return’ and before ‘{‘.

function getObject(){
    return
    {
        param: 5
    }
}

var myObject = getObject();
gs.print(myObject.param);

This time if we execute this code in background scripts the result will be undefined:

That happened because JavaScript automatically added a semicolon after ‘return’ according to the third rule of automatic semicolon insertion. The full description and all three rules of automatic semicolon insertion you can find in ECMAScript Language Specification here:

Rules of Automatic Semicolon Insertion

Finally, our code looks like this:

function getObject(){
    return;
    {
        param: 5
    }
}

var myObject = getObject();
gs.print(myObject.param);

Leave a Reply

Your email address will not be published. Required fields are marked *