hasValue() verses nil()

gflewis
Kilo Expert


hasValue()
and

nil()
appear to serve the same purpose. Is there any situation where they behave differently? In other words, is there a situation where

hasValue() != !nil()
?

If a field contains a bad reference (i.e. sys_id of a non-existent record), does

hasValue()
return true or false?

3 REPLIES 3

MB26
ServiceNow Employee
ServiceNow Employee

From my testing it would appear that hasValue() and nil(), being boolean results, are just opposites to each other. hasValue() returning true and nil() returning false for a particular situation. I did test the bad reference field situation you mentioned. e.g. I created a CI, associated it to an incident, then deleted the ci. When I query the task_ci table with this, I get the below result.



var gr = new GlideRecord('task_ci');
gr.addQuery('task','383982cf0a0a3c18007c3654c72a565d'); // sys_id of the incident record
gr.query();
while (gr.next()) {

if(gr.ci_item.nil()) {
gs.print("NIL: " + gr.ci_item);
gs.print("NIL: " + gr.ci_item.getDisplayValue());
}
else{
gs.print("NOT NIL: " + gr.ci_item);
gs.print("NOT NIL: " + gr.ci_item.getDisplayValue());
}

if(gr.ci_item.hasValue()) {
gs.print("Has Value: " + gr.ci_item);
gs.print("Has Value: " + gr.ci_item.getDisplayValue());
}
else{
gs.print("Has NO Value: " + gr.ci_item);
gs.print("Has NO Value: " + gr.ci_item.getDisplayValue());
}
}

Result:
*** Script: NOT NIL: 951dc14d0a0a3c180103775aab6a2d57
*** Script: NOT NIL:
*** Script: Has Value: 951dc14d0a0a3c180103775aab6a2d57
*** Script: Has Value:

Which also tells me they are merely the opposite boolean results of each other.


john_roberts
Mega Guru

hasValue is a simple method that returns !nil(). Since an orphaned record still leaves a sys_id in the reference field is will appear that is has a value since it does in the database.

If you want to check for a valid reference you can use:
gr.refField.hasValidReference()


I'm trying to use hasValidReference() in a workflow "If" activity but it is returning "false" all the time, even when there are valid entries in the Manager field.



answer = ifScript();

function ifScript() {
if (current.request.requested_for.cost_center.manager.hasValidReference() || current.request.requested_for.cost_center.parent.manager.hasValidReference()) {
return true;
}
return false;
}

I can't find any documentation for that function anywhere.