Javier Arroyo
Kilo Guru

tl;dr

the variable name gr is a perfectly valid name when used within a logically small context. First look at scope and code structure before being fatal about the use of gr. Context means everything. Although I find gr a technically reasonable identifier, I myself don't use it.

                                    ----------------------------------------------------------------------------------

This article will look to provide some context for the valid use of gr as variable name. 

If you are like me browsing through the community, linkedin, developers.com, slack or discord, following MVPs, etc just to catch some snowflakes, you'll soon discover that there seems to be a high degree of polarity associated with the use of gr as a variable name. The crux of argument against it is somewhat rooted in industry standard programming conventions (some are just lack of subject matter knowledge muddied by experience). It's proponents are mostly on the side of familiarity.

Naming conventions say that identifiers should be logical, unambiguous, reveal function content, larger than 3 characters to help convey meaning and help with readability, etc. Those conventions, however, don't apply in a void, they must be applied within the context in which they are being used.

For example, a less addressed convention states that smaller the scope of a variable (how long it lives), the smaller its name can be. It is meant to account for details that accept a one character variable name as equally suited for the task as a longer one. It means to tells us that context, the lifespan should be considered when naming variables. 

It is in that duration that a variable exists that readily reveals when to use GR. If function is 3 or 5 lines long, variable names can shrink as small as a single character. Presuming, of course, that the function is well named. At the level of a short lived variable name, a longer name grants no reasonable or technical advantage over gr. It might even be some sort of non technical win because of familiarity bias. 

However, it is in smelly code that gr truly becomes an obstacle. Smelly code means bad structure, scope, format, all of those characteristics that the slightest addition of ambiguity further damages readability and sanity. 

For example:

getFieldRequirements: function(sys_class, table, state, oldState) {
		var mandatory = "";
		var notmandatory = "";
		var readonly = "";
		var notreadonly = "";
		var visible = "";
		var notvisible = "";
		var isLoad = true;
		if (oldState)
			isLoad = (state == oldState);
		var gr = new GlideRecord(sys_class);
		if (isLoad)
			gr.addQuery("start_text", "");
		else
			gr.addQuery("start_text", "").addOrCondition("start_text", oldState);
		gr.addQuery("end_text", state);
		gr.addQuery("table", table);
		gr.addQuery("active", true);
		gr.query();
		
		// Combine all field requirements that fit this state transition
		while (gr.next()) {
			if (gr.mandatory_fields)
				mandatory += this._translateFields(gr.mandatory_fields);
			if (gr.visible_fields)
				visible += this._translateFields(gr.visible_fields);
			if (gr.read_only_fields)
				readonly += this._translateFields(gr.read_only_fields);
			if (gr.not_mandatory)
				notmandatory += this._translateFields(gr.not_mandatory);
			if (gr.not_visible)
				notvisible += this._translateFields(gr.not_visible);
			if (gr.not_read_only)
				notreadonly += this._translateFields(gr.not_read_only);
		}
		return {mandatory:mandatory, notmandatory:notmandatory, readonly:readonly, notreadonly:notreadonly,
		visible:visible, notvisible:notvisible};
	}

There is all sorts of problems with the function above. And, to add to it, the use of gr to the OOTB code block adds further ambiguity. What exactly is the query returning? We all know it can only return a GlideRecord; and, why wasn't gr named logically accordingly to the expected return? The author has chosen to highlight the least important trait of the variable, its type, over informing the reader what is being returned. In clean code the author of the code block is said to be inconsiderate, as he has preferred effort of naming the variable over conveying his intentions. Does it really matter that the query is a GlideRecord when the reader still has to analyze and reason the entire cryptic construct?

That function is the sort of coding that leads to the ultimatum to "never, ever use gr". But, the basic issue here is poor structure and mixture of concerns that create one of those wtf moments (it is said the readability of code is best determined by how many wtf come out when first looking at a function). If this is the type of code that we are used to, then it becomes perfectly understandable why some coders believe not using gr as an identifier can help fend off bugs. And they are right, we are so institutionalized to poor code that we don't even that it's become the acceptable practice, only fixed with superficial adjustments.

The code block isn't asking for better variable names, comments, or formatting to improve it. It's really begging for tender love and care to reduce it to a manageable construct. It's simply doing too much to have, say, gr  replaced with activeFieldsByState help it in any meaningful way. The reader still left wondering what is happening. 

 

Reasonable use of gr 

function allOpenIncidentsByUser (sysUserId) {

    var gr = new GlideRecord('incident');
    gr.addEncodedQuery('active=true^caller_id=' + sysUserId);

    gr.query();

    return gr;
}

In the code fragment above, gr lives for precisely four lines. The function name identifies what the function body is doing clearly enough that there is no need to somehow reiterate part of the function name in the variable. It might make folks like me feel better that the variable is named "logically", such as openedIncidents but, the fact is that it doesn't help or hinder readability of the code. gr works just as fine as a longer name. 

If the issue is the lack of readability for gr, then the issue isn't the variable but the structure and architecture. They must change to improve readability. This means a wrapper to GlideRecord to be leveraged in all sorts of ways as to bring code language closer to English grammar. It could then transform to: 

function allOpenIncidentsByUser (sysUserId) {
   return DBTable('incident').query('active=true^caller_id'= + sysUserId);

}

or

function allOpenIncidentsByUser (sysUserId) {
   return SysUser().myOpenedIncidents(sysUserId);

}

Final thoughts

Next time someone expresses some sort of truth about gr try to find out the content in which the argument for, or against exists. The context will make the difference understanding the argument. 

So. While I don't use it myself. It's well informed and intended use is as valid as my preference not to use it even in small functions.

Comments
Allen Andreas
Administrator
Administrator

Hi,

Appreciate the article.

To me...I use gr here and there, but I wouldn't rely solely on it. I do so more on the forums to use an example. The person that example is for, is up to them to take it and run with it from there.

Per ServiceNow though...they say this: https://hi.service-now.com/kb_view.do?sysparm_article=KB0713029

So...while I get your article and appreciate the effort...it won't solve the age old question about gr and to use it or not nor should anyone other than ServiceNow try...in my opinion.

Sorry!

Jace Benson
Mega Sage

The problem isn't the "gr" is bad by itself, the problem is if any old business rules declare gr in a global context it steps on your "gr". 

So even if the code is small, 3 to 5 lines, depending on the table, you have things like this to deal with.

find_real_file.png

I didn't make this rule up.  It's in my PDI out of box.  you run you're script against sys_user_group with an insert or an update and your gr variable will be stepped on.  Use it if you must, but please don't.

Javier Arroyo
Kilo Guru

The SNow article about gr is well known. It in fact underlines  my point. Bad code leads to bad issues. There is so much bad code in ServiceNow that a variable name could have unintended consequences. The problem then isn't the variable name, it could have been called records then records would have been considered a bad practice. It is that any variable name in a global scope can cause all sorts of issues.

From the article:

"General good javascript coding practice would avoid most of these issues.

You could wrap your scripts in a function to avoid your script clobbering another gr, which is why new business rules, calculated fields, etc. mostly now have a default script added to wrap the code to protect the variables within the function, but most scripts and including older business rules don't require this. Wrapping your code in a function is good coding practice, so always do this."

It's basically saying, "hey, gr is okay. just learn to program". 

In regards to using it or not. It is only in the ServiceNow community that a two character variable identifier is considered a bad practice, 100% of the time, even properly used and enclosed. To the programming community at large, scope dictates the size of the variable name. For example, single characters in loops, or less than a hand full of lines.

Such as:

function doALoop (items) {

  for (var gr=0; gr < items.length; gr++ ) {
      //do something
  }
}

 

var trace = x => console.lgo(x);
function counter (x) {
   return x + 1;
}
function identity(x) {
  return x;
}

Here is an example from the Java Spring Framework

	@Override
	public void setValues(PreparedStatement ps) throws SQLException {
		if (this.args != null) {
			for (int i = 0; i < this.args.length; i++) {
				Object arg = this.args[i];
				doSetValue(ps, i + 1, arg);
			}
		}
	}

and another one

public static void setParameterValue(PreparedStatement ps, int paramIndex, int sqlType,

@Nullable Object inValue) throws SQLException {
	setParameterValueInternal(ps, paramIndex, sqlType, null, null, inValue);
}

 

See the use of ps. That the same as gr. This  points to structure, and clean code. Because the Spring Framework limits its functions to about 4 or 5 lines. Double digit variable names are perfectly acceptable. They create zero ambiguity.

The difference between systems is, of course, code architecture. 

Jace Benson
Mega Sage

By avoiding that variable name you avoid the problem all together.

The SN Nerd
Giga Sage
Giga Sage

Thanks for taking the time to write this provokative article.

I think the use of gr is 'acceptable' under the following circumstances:

  • When the variable is used as a generic GlideRecord that could be for any table with parametised queries
  • When it is used within a Self Invoked Function or Function/Class scope (ie not in a Business Rule, as per the issue raised by jacebenson)
  • When there is only a couple lines of code and the function name clearly describes what gr is used for

So in the code you have provided, I don't have an issue - as GR is truely generic and embedded within a class. When people say 'Never do X' - there is usually at least one circumstance where it isn't really an issue to do so. 

In all other circumstances in exclusion of my above points, I would recommend using meaningful variable names at all times. I'd usually prefix these with gr.

Javier Arroyo
Kilo Guru

We are tying to avoid problems that in well written structured custom code won't cause a problem.

My defense isn't whether to use it or not. It is: know what you are doing. If how, what and why, the system can be peppered with global variables and your code won't affect them. GR is being picked on, and its use as a global variable an excuse to support lack of knowledge of scope and variable shadowing.  

Javier Arroyo
Kilo Guru

I share your views Paul. It's an extremist position that arises from misunderstanding of programming. It's not a harm having that view, I don't like the name myself but, the arguments against it just don't jive. Including being a global variable. 

There is more than one global variable in the system yet, those aren't a problem. Why aren't current, previousglobal amongst many others, not such a big issue? Why aren't there docs with a list of variable names to avoid because they are global? It simply doesn't make sense. A better approach would be education.

That the community avoids some practices because scoping and variable shadowing isn't understood is a deeper issue than the use of a confined variable name.

 

Allen Andreas
Administrator
Administrator

You're missing the point.

You're missing my point.

No one is saying literally the letters g and r put together...is the problem in a code sense anywhere in the world...and certainly they aren't saying that 100% of the time on the darn forums dude...like c'mon now...

As Jace mentioned below...it's because within ServiceNow...THEY have used gr...all over the place...that that is why it's not best practice to use it.

Period.

Also, as a side note, I'm not seeing where people are running all around saying GR is bad GR is bad...like it's some major thing. It's just something that gets brought up from time to time...

I'm on the forums quite a lot, I don't see it that common that it needs to be blown in to all this, honestly. Saying stuff like extremist views...and 100% of the time people are saying this and that...don't start fluffing statements and oveeerrlly exaggerate things to make a point. Stay the course. Make your points with facts and stay true.

Allen Andreas
Administrator
Administrator

Precisely. Thanks Jace!

Allen Andreas
Administrator
Administrator

Extremist...my goodness...

Nope, I think you yourself didn't know of or understand yourself that:

ServiceNow themselves has advised against gr...

The community didn't randomly come up with it. It started with ServiceNow and it boils down to a simple reason:

We (SN) used it in this method...people saw the OOB code, used that as "templates"...but...in doing so, issues arose with gr being a common problem...so articles and such came out advising against it.

That's really about it...

It not some kool-aid the community is drinking and just blindly following it...it's just BEST PRACTICE (not JavaScript...not "coding"...just a SN best practice)...to avoid it.

You also dropped in "MVPs" in your article...well...3 of them are here and we're all saying the same thing basically. You can use it, but don't rely on it. Not best practice to use it. Echo, echo, echo.

Not everyone that uses the forums is a pro with ServiceNow. One of the reasons people are here on the forums is because they aren't and want to learn and grow. Yes...a more "advanced" scripter can wrap everything in functions and be a-ok...but that's an additional step that not everyone does...so...it's far easier to just explain that using gr isn't necessarily recommended.

But again...no one is shouting from the rooftops about it, it's really more learned the longer you're around. And it's usually learned when a problem comes up and rarely...yes...gr is the problem, but you can avoid it altogether, by just not using gr.

I get what you're saying, I do...and I appreciate you trying to explain it, but I wasn't going to NOT saying anything about it...especially when ServiceNow themselves recommend against it (even if it's like: hey...we're gonna help you....help yourself...because you probably won't do it right...so just don't use it).

As people get more experienced, then they can see that they can use it, correctly.

So while your article has good points and tries to help explain things...it didn't at all cover WHY ServiceNow has said to not use it.

Instead...it actually comes off as if it's absolutely unfounded and just a myth that you wanted to clear up. There is actually "logic" around it and there's a reason for it. Which is why I posted.

If you had stated both sides of the coin and showed why ServiceNow recommends against it and how YOU'D like to explain your side and show us how it's done...the article would have been better received...as least by me.

Instead, I mention the article, you say it's "well known" (yet...you didn't mention it yourself, talk about it and it only has like 1k views...) and proceed to run down the road about variable length and this and that.

You are correct. Not arguing that.

I am arguing that there is a reason for the gr discussion (whenever it does happen)...and there's logic and explanation behind it. That's it.

Jim Coyne
Kilo Patron

And that's precisely why you should protect your code using the Immediately Invoked Function Expression (IIFE) design pattern, also known as a Self-Executing Anonymous Function (S-EAF).  Doing this protects your code from other code in the global scope and maybe more importantly, protects other code from yours.  🙂

I've written about this a long time ago - Self-Executing Anonymous Functions.

I'd really like ServiceNow to dedicate one release to cleaning up crap like this instead of adding a bunch of new features.  I know, I know, not very sexy, but would help lower my blood pressure.

DrewW
Mega Sage
Mega Sage

I agree Allen, I remember "back in the day" when none of the business rule code was wrapped in separate functions.  I can remember several times not using gr for a variable name and then having an issue because the var name I choose was used in another BR that ran that was not wrapped in a function.  Any var name can have the issue that gr had/has, especially back then. 

 

DrewW
Mega Sage
Mega Sage

I SOOO agree with your last sentence.

Javier Arroyo
Kilo Guru

Mate,

My experience is to the contrary.  Browsing about gr in mvp posts, even bring it up (such as in this post) brings about black/white stances. Your strong words emphasize how touchy a subject it is.

I can assert that if anyone were to browse MVP videos, read their posts, especially those that concentrate on code, it will undoubtedly support my stance: The continued statement that gr is an inherently bad practice. If I were incorrect, why has it become a "Best practice"? Just like you and Mr. Jace have tried to instruct me by using ubiquity as a supporting defense against its use. 

Ubiquity doesn't provide technical grounds for disproving the use of gr. Instead, there should be some well formulated example of what, why and how it is being affected. However, that example will have to be a misuse of basic javascript practices to be valid, a statement more about the coder than the code.

My stance is that it takes a deep lack of programming knowledge, even misuse of SNow own best practices, the believe that gr can/will cause any problem because it's used everywhere.

In the programming world there is an adage that says something along the lines of "reason before best practice". 

To me, considering the amount of times a variable is used (globally or not) in a code base, as poof of increased likely-hood of bugs, even future availability, strongly highlights a lack of understanding about coding. It is in indictment of the person.

Jace's point supports only that the variable is used globally, not that custom code will affect it. His point doesn't disprove that the variable doesn't have it's place and time of use.

To me, a best practice should be technically supportable. Strong opinions should instead become preferences. 

Best practices

  IIFY to create scope
  SIs to order code and increase re-usability
  ASYNC to reduce wait times
  wrap all code in functions

SNow prefers gr not be used because the level of coding skill in it's population, and terribly built code base will cause a problem.

I simply can not subscribe to a belief that uses language unawareness to support a claim.

Javier Arroyo
Kilo Guru

Love your stance, Jim.

SNow should had made this a priority long ago. 

One can only presume that as upgrades happen, new scoped functionality will sunset the existing mess, making the priority of fixing them a secondary thought and headache for developers.

Javier Arroyo
Kilo Guru

Allen, thank you for asking me to consider all sides of a problem in order to write clearer posts in the future. I should have touched upon it. I seriously didn't even consider it. It is such an obvious point that it lapsed my judgement completely. It would have a made a difference

I must say though, a 1K article in a SN is really a well known article. 

I disagree with your stance for the recommendation against it. Your position grows weaker the further you explain it; the less technically supportable it becomes. If it is not a coding problem, then why even have a variable name be considered a best practice? There is only one way to encounter the issue, and it is through bad code. So yes, its solution and error is fully grounded in JavaScript.  

See, the best practice is promoted because there is less effort involved for SNow. Its simply easier to let nontechnical folk that technology is affected by not  knowing what you are doing. Best stay away from x, y, and z all together. Until proven otherwise, the argument is fully grounded in programming ignorance.

As a community, our goal should be directed towards an elevated degree of knowledge. We shouldn't be supporting vendor efforts by ourselves not teaching. It's alarming to me that 3 MVPs have used anecdotal support, and technical level of the developer community to prove an disprovable technical issue. It's as if we don't have desire to help. 

If, as a community, we want to increase the level of knowledge, Best Practices must be reconsidered, dissected and explained, even if the effort is too great.

From aspen onward, there should have already been a visible progression from the community toward knowledge of its "civic" language, where today the name of a global should have been an after thought. Yet, we consider the most basic of JavaScript issues an issue because "This is ServiceNow". It's as if the platform were some sort of entity where the laws of physic worked differently and needed it's own set of rules. Yup, JavaScript here behaves like C and there like python.

Don't group preference with technical knowledge to forgo a chance to teach. Next to every article, every class, every claim about gr, there should be technical solutions. Teach, teach, teach!

Staying away from it doesn't teach! It hinders technical growth. What does it matter to anyone that a variable is global or used everywhere? Such trivialities doesn't matter to anyone else in any another other scoped language. Why, in orlando, is this still an issue? It's the same symptom and cause for the best practice of "don't delete a native artifact". 

I refuse to be at the point where an SN representative (user, developer, MVP, etc) stands in front of a technical audience and claims that a platform best practice is for a global variable gr not to be used because it is everywhere in platform. This raises an incredible amount of questions about the platform and it's developers. It does not matter how much the variable is used, nor where. Not at all! If you prefer it because you don't trust yourself, then okay, good. I can understand that. But, that's not Best Practice even if you don't know JS. 

In about 10 years in the platform, I've written more lines of code that anyone should write in a lifetime, yet I have never ran into a problem with gr. If the best practice was to truly helping me solve a technical issue, it should have broken something by now. Let's just make it a reserved word. Now, I'll back the idea that is a best practice not to use it.

It is knowledge that I'm after. Not being right, nor to trying to prove my point by making stories up.

If you have a technically supportable stance that shows how gr properly used in your code will cause a problem, then I will rewrite this post and will have, in the process learned something I lack.

But, if your stance is that you are trying to prevent people from issues by not teaching them that a lack of knowledge in any topic will affect them somehow, then... I can't agree with you.

 

 

Javier Arroyo
Kilo Guru

Some POC using the BR raced by mr. jace

find_real_file.png

 

The business rules:

On after order 50

find_real_file.png

 

 

On after order 101

find_real_file.png

 

The technically sound best practices then can be

. all variables must be declared using var
. logic should not be found in BRs
. ALL logic should make its way into a SI
. BR code should be a one line call to an entry point function in script include
. Shadowing and Scoping affect variables. (From where they'll be visible)
. JS5 has two scopes, Global and Local.
. use strict mode

A local variable with the same name as another won't override a global variable.

 

gr has been made a problem because BRs and the global scope are part of an ill advised architectural decision. SN should have never allowed their artifacts to be touched, never allowed custom code inside BRs. They should have closed the global scope, given a way of re-writing a BR by using a field to call a function from a SI.

IMHO, it is obvious that those who build OOTB JS during the early stages of JavaScript didn't know the language. Despite all of that, it is still not a problem.

There is no reason to disseminate Best Practices that are answered with the most basic of JS principles because our platform is different.

Jace Benson
Mega Sage

There's two problems I have with using the variable, specifically "gr".

  1. The variable name means nothing.  Sure you can say it means GlideRecord, but GlideRecord of what?  I don't always name things well, but I do always name these things around the table they are on because it makes the code easier to follow, and faster to make sense of.  Maybe an unpopular opinion but i generally name my variables about what they are, e.g. a GlideRecord for incident, I will name `var incident = new GlideRecord('');`
  2. Unless you are disciplined and ensure where ever you write you use function scoping, you may end up with issues.  This is not helped when ServiceNow themselves only continue the problem.  If you go today to write a fix script to correct some date, you are only given a empty script field.  At minimal, those should default a wrapped function of sorts. Same for Background - Scripts, Access Controls (script field), Workflow (Every field with a script field), I'm sure there's more places, point is, some of them don't default with function scoping, and some even require an output in globally called variable, see Access Controls and the the `answer` variable.

I do also want to add, we may disagree on things here, but I do love the posts you make and think its great to have this back and forth. 

Maybe a happy medium is setting up the linting in ServiceNow, however that wont help you where script fields are plain and don't show the scripting stuff.  Personally, if it doesn't catch everything, any action taken seems not enough.

In trying to identify why I avoid gr as a variable I did some soul searching.  It turns out, I like variables that make sense to me.  I found this rule that Google has on their JS styleguide is pretty much on par with my opinion about how to name something.  Airbnb style guide has similar rules.  So looking in hindsight perhaps I should have said, "using a meaningful name helps you in two ways, 1, it avoids these problems if you're working in a unwrapped code segment, 2, it makes the code more immediately understandable by a new reader."

John Caruso
Kilo Guru

tl;dr

If you encounter a naked script field clothe it with an IIFE to avoid the harmful evils of the global scope:

 

 

(function () {
    'use strict';
    // Add your code here, e.g.:
    // don't worry my little gr, those global scope bullies won't clobber you!
    // you're safe and sound inside this local scope
    // and please ignore those people saying you should change your name, it's a fine name!
    // just don't stray too far from your assignment and all will be well
    var gr = new GlideRecord('sys_user');
})();

 

 

Javier,

Thanks for writing this article! I really appreciate your effort to distill the nuances around variable naming and scope.

Jace,

Thanks for tweeting about this thread and bring it to my attention.

Allen,

Thanks for linking to the KB article "Best Practice: Why using 'gr' as a GlideRecord variable name in custom scripts is always a bad idea". I had not seen this before.

---

To fan the flames of this thread a bit more, I'd like to highlight a couple extremist statements from the KB article author:

  • Using "gr" as a GlideRecord variable name is always a bad idea
  • Using "i" as a for loop counter everywhere is also bound to cause trouble sooner or later

It is time for all of us to submit GitHub pull requests to rename for loop index variables for 6 million+ lines of open source JavaScript?

Uhhh... NO!

If the actual problem is global scope pollution, renaming things won't solve it. 

A global scope grIncident is just as easily clobbered [see Clobbering if this l337 jargon bewilders] as gr especially if your whole team follows the same convention and grIncident appears in numerous scripts that might share the same global scope.

Don't fool yourself. Educate yourself.

The only real value of the KB is showing via the "real world example" and related problem tickets how bad things can get when you use global scope variables.

I'd ignore the extremist positions taken by the KB author and follow their less extreme advise: 

  • Wrapping your code in a function is good coding practice, so always do this.

But please ignore the "always". Sometimes using global scope is unavoidable.

When you do, don't use gr as a variable name. 😉

The SN Nerd
Giga Sage
Giga Sage

Great summary.

lcbell
Tera Expert
clobber, clobbered, and clobbering are not accurate software engineering terms. the correct terms are overwrite, overwritten, and overwriting
 
Each variable defined in function scope is totally separate from any other variable in global scope as long as you use the var keyword to define it in function scope. You should read and understand https://github.com/getify/You-Dont-Know-JS/blob/2nd-ed/scope-closures/ch1.md
Instead of using a named function that is immediately called, you should use an Immediately Invoked Function Expression. See https://developer.mozilla.org/en-US/docs/Glossary/IIFE
Using an IIFE will not pollute global scope with the function definition and will encapsulate all the variable and function definitions within the IIFE.
 
To prove my point run this code:

 

var gr = 'this is defined in global scope.';//this is a variable definition that happens at compile time with a variable assignment that happens at run time

(function () {
     console.log(gr + ' there is nothing in the function scope variable gr yet' );

     var gr = 'this is defined in function scope.';//this is a variable definition that happens at compile time with a variable assignment that happens at run time

     console.log(gr + ' now there is something in the function scope variable gr' );
} ) ();

console.log(gr + ' see nothing in the function scope altered the global variable gr' );

 

and the output is
undefined there is nothing in the function scope variable gr yet
this is defined in function scope. now there is something in the function scope variable gr
this is defined in global scope. see nothing in the function scope altered the global variable gr

 

 

 
You can clearly see that within the IIFE, the function scope variable gr is not assigned but is still defined on the first console.log statement. This is due to hoisting when the code is compiled, which creates two variables named gr but they are in totally different scopes.
So in the second line of the IIFE, the function scope variable gr is assigned a value. This does not affect the global variable gr at all. You can clearly see that in the third console.log statement.
 
Now if within the IIFE we didn't use the var keyword, we wouldn't define a function scope variable gr but would reassign the global variable gr.
 
To prove my point run this code:

 

var gr = 'this is defined in global scope.';//this is a variable definition that happens at compile time with a variable assignment that happens at run time

(function () {
     console.log(gr + ' this uses the global variable gr' );

     gr = 'this is reassigned in function scope.';//this is a variable assignment that happens at run time. it uses the variable defined in global scope

     console.log(gr + ' now the global scope variable gr is reassigned' );
} ) ();

console.log(gr + ' see the function altered the global variable gr' );

 

and the output is
this is defined in global scope. this uses the global variable gr
this is reassigned in function scope. now the global scope variable gr is reassigned
this is reassigned in function scope. see the function altered the global variable gr

 

 

 
So you can see that there is nothing wrong with defining a function scope variable with the same name as a global variable or a variable in any other function.
 
To prove my point run this code:

 

(function () {//function scope 1
     console.log(gr + ' there is nothing in the function scope 1 variable gr yet' );

     var gr = 'This is defined in function scope 1.';

     console.log(gr + ' now there is something in the function scope 1 variable gr' );
} ) ();
try {console.log(gr);}//this is an error since gr is not defined outside the IIFE
catch (ex) {console.log(ex); }

(function () {//function scope 2
     console.log(gr + ' there is nothing in the function scope 2 variable gr yet' );

     var gr = 'This is defined in function scope 2.';

     console.log(gr + ' now there is something in the function scope 2 variable gr' );
} ) ();
try {console.log(gr);}//this is an error since gr is not defined outside the IIFE
catch (ex) {console.log(ex); }

 

and the output is
undefined there is nothing in the function scope 1 variable gr yet
This is defined in function scope 1. now there is something in the function scope 1 variable gr
ReferenceError: gr is not defined
undefined there is nothing in the function scope 2 variable gr yet
This is defined in function scope 2. now there is something in the function scope 2 variable gr
ReferenceError: gr is not defined

 

 

 
So you can see that the first variable gr (in the function scope 1) does not exist outside the first IIFE so there is absolutely no way it can be affected by any other variable with the same name in any other function scope or global scope.
 
Defining a variable with ANY valid name inside a function is always ok, even if you have the same name in multiple functions.
 
If the following is in the same scope

 

var gr = '1';
console.log(gr + typeof gr);//output: 1string
var gr = 2;
console.log(gr + typeof gr);//output: 2number

 

What is gr before the first line? undefined
The third line does NOT define a second variable. The scope only has one variable named gr. The compiler sees that gr was already defined in this scope so the second var is ignored. gr is overwritten.
 
I do a lot of coding, so I reuse a lot of the code for GlideRecord. It is much easier to write and maintain the code if I use the same variable name for my GlideRecord. It would waste a lot of time if I had to rename my GlideRecord variable every time I used it. It also makes searching for code faster and easier.
 
I've already proved that reusing the same variable name is not a problem.
 
The real issue is learning exactly what is going on in the code you are writing and what can cause problems.
 
Making a blanket statement like "using 'gr' as a GlideRecord variable name in custom scripts is always a bad idea" is just wrong. That statement doesn't explain the truth or teach people but is a way they try to cover up the fact that they have really bad code and have polluted the global scope with really bad variable (and function) names.
Version history
Last update:
‎04-16-2020 02:52 PM
Updated by: