Tuesday, July 23, 2019

Javascript, using one single local object instead of many local variables

I often use jslint and tools to verify my code for programming errors, etc...



During the course of my programming I often find that I need a local variable or a local function to do some simple things. So I go to my main single var statement at the top of my local scope and adjust it, sometimes breaking my creative flow. So sometimes instead I declare a single line var in the middle of my code to continue my programming and then move it at the top var statement during refactoring afterwards.




I had an idea today that i want to explore and did not find anything on it on Google or stackoverflow.



My idea is this, just declare a single temp object and use it for whatever the need. Ex: adding some attribute for a new variable or function.



So instead of :



// if I omit the last comma, the next variable will be a global
var variable1 = "Hello World!",
variable2 = "Testing...";


(... some code ...)
var variable3 = 42;


I would instead use :



var temp = {};
temp.variable1 = "Hello World!";
temp.variable2 = "Testing...";


(... some code ...)
temp.variable3 = 42;


So I do not risk polluting the global namespace, I declare variable as needed and do not struggle with that var statement since I always know that a variable preceded by "temp." is in the local scope.



Any comment or advice will be appreciated.

No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...