Rich-text Reply

Protecting global JS variables needed?

lkraav 02-07-15
Accepted Solution

Protecting global JS variables needed?

[ Edited ]

So let's say I'm exploring window.optimizely.data.experiments[experimentID] from Global Javascript for every test.

 

Every test wants to use the same variable naming convention for ease of implementation, so would have:

 

var experimentID = TAKE_ID_FROM_EXPERIMENT_URL;

 

If multiple tests are executing their global JS on the page, is there danger of any test's experimentID value being overwritten by another test executing its global JS, as a race condition?'

 

I would assume that doing this would guarantee absolute safety:

 

(function() { var experimentID = TAKE_ID_FROM_EXPERIMENT_URL; });

 

but is it actually necessary to wrap ourselves with an anonymous self-executing function for this particular purpose?

--
Leho, marketing & tech architect | G+: lkooglizmus@gmail.com
Level 4

Joel_Balmer 02-09-15
 

Re: Protecting global JS variables needed?

Hi Leho,

This sounds like an interesting use case! Can I ask you more specifically what you're wanting to achieve - perhaps someone on the community will be able to provide some advice?

But yes that's correct, if you have 'experiment (global) javascript' for 2 different experiments writing to the same variable name, it will overwrite because it will be defined in the same scope. And yes, an alternative is if you're wanting to use the variable within the scope of the function only.

For this reason, depending on the use case, it might not be recommended to run certain code on several 'experiment javascript's for fear of a conflict.
lkraav 02-14-15
 

Re: Protecting global JS variables needed?

Topic is adding another GA integration for backup using events https://gist.github.com/lkraav/2ac6f6aef6d3d0a2fb71
--
Leho, marketing & tech architect | G+: lkooglizmus@gmail.com
Level 4