The Zurich release has arrived! Interested in new features and functionalities? Click here for more

script to check if a variable exists

Aka Guglielmo
ServiceNow Employee
ServiceNow Employee

Do you have any idea on how to check, inside a workflow, if a variable exists?

Let me say, something like: if (current.variables.variableName.exists).

Because if (current.variables.variableName != '') returns an error.

Thanks

1 ACCEPTED SOLUTION

I suppose an even easier way is just to test it.



if (current.variables.var_name) {


        // The variable exists and is not null


} else {


        // The variable does not exist


}



The same can be done with fields as well to avoid null pointer exceptions. See the best practices.



Reference:


ServiceNow Wiki: Technical Best Practices


View solution in original post

13 REPLIES 13

Hi Chuck,


I tried to implement but i am half way through.



Steps followed:


Cloned the widget "sp-variable-editor" and created a copy in global scope.


Created a record in "sp_ui_formatter" table and pointed the cloned widget with the macro of SM variable editor.


I am able to get varibles on the Service portal form but they are empty.



Could you please suggest me something that would help me fix this issue.



Regards,


Zabeeulla.


tkaneko
Giga Contributor

Another alternative if you have a situation where you need to see if the variable exists but the value may be empty or null is to use the following:



if (typeof(current.variables.var_name) !== 'undefined') {


                    //See if the variable exists regardless if there is a value present



                  if(JSUtil.notNil(current.variables.var_name)){


                            //If necessary check if there is a value (otherwise omit this if statement)


                  }



} else {


        //The variable does not exist


}


Catalin2
Kilo Contributor

The safe way is to use native Javascript function - you can use for existence of any property of an Object.

You can check for if a variable exist with current.variables.hasOwnProperty(variablename). If is false, means that you don't have that variable.

 

 

LA_
Tera Expert

How can I incorporate this in Flow Designer whether via Flow Logic or Custom Action? I have a flow that should check if the "approver" catalog variable exists first, before triggering the "Ask For Approval" step.

thanks in advance.