psphanindrakuma
Tera Guru
Tera Guru

Hi All, I'm starting a new series of short and interesting articles. This is the first one in the series. I hope you will like it.

 

Have you ever faced it when you try to assign a field to a variable and it results in an empty value?

var field = current.fieldname; 
// OR 
var anotherVariable = gr.another_fieldname; 
// It prints nothing. NOTE: It may print something in background scripts. 
//But it will not work as expected while using scripts. gs.info(field); gs.info(anotherVariable);

And sometimes assigning field values to variables works fine. Why?

var field = current.fieldname + "Example"; 
// OR 
var anotherVariable = gr.another_fieldname + "Example"; 
// It prints something as expected. 
gs.info(field); 
gs.info(anotherVariable); 

Surprised!!!!

I will tell you why.

We all know ServiceNow uses Javascript.

We define variables in JavaScript, and the current or previous object or variables that are invoked by GlideRecord are Java objects because GlideRecord is a Java class.

So, there is incompetability between them. The Javascript interpretor does not understand Java objects. But the Javascript interpreter understands it is an object, but it doesn't understand what it is returning. This is why we get an empty object in the javascript variable.

 

How can we overcome this?

We can privent this by using getValue('fieldname') or getDisplayValue('fieldname') or concatenating with an empty string (i.e., ""/'').

In Javascript, the + operation will do magic. It will convert one data type to another.

  var field = current.getValue('fieldname'); 
// OR 
var anotherVariable = gr.getValue('another_fieldname'); 
// OR 
var another Variable = gr.getDisplayValue('another_fieldname'); 
// OR 
var someotherVariable = gr.someother_fieldname+'';

Happy learning..!!!!

My Articles:
1. Useful Number methods in JavaScript
2. Service-Now Client Script APIs 
3. VS Code setup for servicenow

4. Useful String Methods

 

I hope this article helpful. Please mark it as helpful and bookmark if you like it.

 

Develop a passion for learning. If you do, you will never cease to grow.” — Anthony J. D’Angelo

 

Thanks,

Phanindrakumar Pulletikurti.

Comments
Sanjana2
Tera Explorer

This is a great article. All developers have to go through it for better scripting practices.

Very useful, great job.

test271
Tera Contributor

This is a super useful article for reference. 

Version history
Last update:
‎10-04-2023 06:56 AM
Updated by:
Contributors