javascript noob Q - set global variables for current page

  • 1
  • Question
  • Updated 4 years ago
  • (Edited)
Is this post correct? 

Can I set a global variable inline that is not within any function and use this variable anytime I choose so long as I don't refresh the page?

For example, can I run a snippet which sets the value, so something in a popup, then run another snipper that used this global value.
Photo of mB Pat Vachon

mB Pat Vachon, Champion

  • 42,714 Points 20k badge 2x thumb

Posted 4 years ago

  • 1
Photo of Irvin Waldman

Irvin Waldman, Champion

  • 9,006 Points 5k badge 2x thumb
Pat,

With JavaScript, the global scope is the complete JavaScript environment.  In HTML, the global scope is the window object: All global variables belong to the window object.  So you could do something like this

var isDude = 'Pat';
alert(window.isDude);

-or-

if (!window.isDude) { window.isDude = 'Pat; }

Best practice is to not use global variables.

I am not a JavaScript developer so nothing said or written comes with an expressed warranty.

google-bing for lots of details and opinions.

Irvin
Photo of mB Pat Vachon

mB Pat Vachon, Champion

  • 42,714 Points 20k badge 2x thumb
I wouldn't use a global variables in snippets could take in parameters when being called from an action.