GlideRecord insert. Is .initialize() necessary?

Kyryl Petruk1
Tera Expert

Hi Everyone,

 

I've just been curious.

Wiki says this is a correct way to insert a record in a table using GlideRecord:

http://wiki.servicenow.com/index.php?title=GlideRecord#Insert_Methods

var gr = new GlideRecord('to_do');
gr.initialize(); 
gr.name = 'first to do item'; 
gr.description = 'learn about GlideRecord'; 
gr.insert();

 

But what actually gr.initialize() does?

What happens if I skip it? Will the record be created differently or simply slower?

On practice I don't see any difference, record is created properly.

 

Will appreciate your comments!

Thanks!

29 REPLIES 29

To add on this conversation. What is the difference between initialize and newrecord?


Initialize() doesn't set default values.


newRecord() populates the record with default values.



Also, isNewRecord() returns true for records where newRecord() has been called, even if the record hasn't been inserted yet.
isNewRecord will return false if you have just called .initialize()



In a nutshell:


.newRecord() - use if you want default values to be populated.
.initialize() - use if you don't want default values to be populated.



ServiceNow Nerd
ServiceNow Developer MVP 2020-2022
ServiceNow Community MVP 2019-2022

Then what's the point in using initialize right after constructing a new GlideRecord?


Another difference:


.newRecord() - use if you need to evaluate .canCreate() field level ACL checks.



ServiceNow Nerd
ServiceNow Developer MVP 2020-2022
ServiceNow Community MVP 2019-2022

m_servicenow
Kilo Contributor

Hey Kyryl,


ServiceNow suggests best practice and it is supposed to write initialize() function when you are making any glideRecord query and writing some query.



There is no more effect in output but it is best practice to use initialize() function.



Either you can or can't. Not affect your output.



But Remember don't use in loop.