-1

I have a number of scripts that I need to pass a url parameter to. I also have a number of pages that (static) pages that require me to hardcode the domain/subdomain of the local environment.

What I want to do is store the url within a global variable so that I have to change the url in 1 place to feed the various scripts downstream that rely on it.

I thought about a simple globals file that contains, for example:

var myURL = 'http://www.google.com'

I'll have additional urls, but I plan to follow in kind with those.

I've heard that this is not good practice, but what's the alternative given what I'm trying to do?

dentalhero
  • 689
  • 3
  • 10
  • 30
  • Yes, It's fine as long as you keep it uniq. If not nobody would use any library or CDN If nobody did it. stuff like polyfill would not exist either. jQuery dose it so what is so wrong about that? – Endless Oct 16 '16 at 00:11
  • Possible duplicate of [I've Heard Global Variables Are Bad, What Alternative Solution Should I Use?](https://stackoverflow.com/questions/2613310/ive-heard-global-variables-are-bad-what-alternative-solution-should-i-use) – Liam Aug 09 '19 at 15:29

2 Answers2

3

If you really have to have some global configuration, I'd stick it in an object / class so you could restrict your use of global variables to the minimum necessary, e.g.:

var Config = {
    googleUrl: 'https://google.com',
    otherUrl: 'http://example.com',
};

That would be better than having a global variable for each thing.

I've heard that this is not good practice, but what's the alternative given what I'm trying to do?

It might be worth explaining your use case a little more. For instance is it appropriate for these URLs to live in JavaScript configuration or do they belong to a specific UI component? If so should the UI component specify the URL on a HTML element as a data-attribute? If they belong with a specific JS module, should they be local variables for that module?

I also have a number of pages that (static) pages that require me to hardcode the domain/subdomain of the local environment.

Could you not use window.location.hostname for those?

JVDL
  • 1,157
  • 9
  • 16
  • Thanks, Dymos. It's appropriate in my mind to live in the javascript configuration since they are essentially agnostic - meaning void of any ui component or module constraints. This worked well for me. – dentalhero Oct 20 '16 at 00:21
-2

I might be wrong, but I don't know why this should be a problem, as long as you are using constants.

const name1 = value1 [, name2 = value2 [, ... [, nameN = valueN]]];

Edit: But at the end you should avoid using global variables, because they could cause some problems at later debugging.

Device
  • 574
  • 4
  • 19