JavaScript Variable Scoping

Any Tag code delivered through Ensighten Manage (or simply Manage) is delivered inside of a try/catch function so that Manage can prevent errors from surfacing to the user's browser and report back to you on what JavaScript errors might be happening on your website. As a result, JavaScript variables used in tags in Manage are scoped locally unless explicitly scoped globally.

Local JavaScript Variables

Local JavaScript variables can only be accessed within the function or Tag that they are used in and cannot be used in any other Tags within Manage or by any other JavaScript that might be on your website.

Referencing s_account will work if you are referencing the variable within the same Tag; however, if I try to reference s_account in a separate Tag or outside of Manage, I will receive an error stating s_account is undefined because the variable is scoped locally.

Global JavaScript Variables

Global JavaScript variables are accessible by any JavaScript running on your website whether it be through Manage or any other technology. As such, global variables should be used sparingly and only when necessary.

To make a JavaScript variable globally scoped, you will need to attach the variable to the window object. If we take our prior example, we would simply use the below code to scope the s_account variable globally.

window.s_account = "acmeincprod";

When using the above code, we can now reference the variable s_account with any Tag in Manage or any other technology.*

* Note that even if you use a a JavaScript variable scoped globally, you will need to use Dependencies within Manage to ensure sure that the variable is defined globally before referencing the variable.