Avoiding strings and hardcoded function names - benefits?
I recently came across a JavaScript script in which the author seemed to be trying to avoid lines inside his code and was assigning everything to a variable.
So instead of
document.addEventListener('click', (e) => { /*whatever*/ });
he will write
var doc = document;
var click = 'click';
var EventListener = 'EventListener';
var addEventListener = `add${EventListener}`;
doc[addEventListener](click, (e) => { /*whatever*/ });
While caching document
to a variable can be viewed as micro-optimization, I'm really wondering if there is another benefit to this practice in general - testability, speed, maintenance, anything?
Legacy IE attachEvent
should be pretty much dead, so being able to quickly make a script in these environments alone can hardly be considered an advantage I envision.
source to share
The example you give looks rather strange and I can't imagine the reason for "good practice" for most of these moves. My first guess was that this was the job of someone who was not sure what they were doing, although it is strange that they would also use ECMAScript 6 syntax.
Another possibility is that it is generated code (for example, the output of some visual programming tool or de-w420>). In this situation, such redundant factoring usually occurs because the code is generated from templates that are conservatively written to protect against errors; I'm thinking about how preprocessor macros in C make liberal use of parentheses.
Sometimes variable declarations are written in such a way that it is clear (to the compiler and / or reader) what type of data is stored in the variable. For example, the asm.js code uses unnecessary variable declarations as a trick to implement strongly typed variables on top of regular JS. And sometimes declarations are written as a form of documentation (if you see var foo = Math.PI * 0
, perhaps you should say that foo
is the angle in radians, since otherwise the author just wrote var foo = 0.0
). But that still doesn't explain something like var click='click'
.
source to share