Immediately Invoked Function Expressions why don't we use them more?

corbettbrasing1
Mega Guru

So if you are not familiar with Immediately Invoked Function Expression you can read about them in these other community articles....

https://community.servicenow.com/docs/DOC-3458?q=Immediately%20Invoked%20Function%20Expressions

https://community.servicenow.com/docs/DOC-2719?q=Immediately%20Invoked%20Function%20Expressions

...but here is my question:   If the point of IFFE's is to keep the global less poluted so that you dont accidentaly reuse variables form other scripts that are running at the same time, then why don't we use them as the defacto, like in every business rule etc that is not calling a script include?   I am aware they that are not needed with script includes because the prototype framework already uses these.     ctomasi  

1 ACCEPTED SOLUTION

I kind of get why they don't include the wrapper around every example in the product documentation. In some cases, the code is generic enough to show an example and apply it in a variety of places (fix script, workflow script, UI action, etc.) When referring to business rules explicitly, yeah, it should be there.



(function executeRule(current, previous /*null when async*/) {



})(current, previous);



You do not need to wrap an IFFE inside the executeRule() function, that's redundant.


View solution in original post

3 REPLIES 3

Chuck Tomasi
Tera Patron

They are the defactor in business rules (since Eureka). They are also showing up in places like ATF scripted test steps. Why they haven't been included in UI actions is still a mystery to me.



IFFEs are a best practice, that doesn't mean everyone is going to use them.


Ok I hear you saying they are defacto in business rules since Eureka but docs.servicenow nor the wiki even use them or show them in any examples that I have found.



Example script: Locking user accounts



But just to confirm...



(function executeRule(current, previous /*null when async*/ ) {//prepoluated servicenow code in busienss rules


        var foo = "foobar";


        //Doo something


})(current, previous);   //WE SHOULD NOT BE DOING THIS



...BUT INSTEAD DO THIS??



(function executeRule(current, previous /*null when async*/ ) {


(function () {


  var foo = "foobar";


  //do something


}) ();


})(current, previous);



It looks like the prepopluated code is actually an IFFE its self, so we dont need to create another one correct?


I kind of get why they don't include the wrapper around every example in the product documentation. In some cases, the code is generic enough to show an example and apply it in a variety of places (fix script, workflow script, UI action, etc.) When referring to business rules explicitly, yeah, it should be there.



(function executeRule(current, previous /*null when async*/) {



})(current, previous);



You do not need to wrap an IFFE inside the executeRule() function, that's redundant.