It seems to me that your code is just busted if you have code paths that attempt to use a global variable before it is defined. Either you need to give it a default value, you need to reorder the loading or execution of your code or you need to prevent code from running when your environment hasn't been initialized.
It is possible to initialize a variable if and only if it hasn't already been defined like this:
var clientId = clientId || "foo";
You could put this at the top of any module that uses it. This would initialize it with whatever value you want if and only if it wasn't already initialized.
You could also build yourself an accessor function that you would use instead of directly accessing the variable like this:
// put this somewhere early in the JS loading process
function getClientId() {
if (typeof window.clientId !== "undefined") {
return(window.clientId);
} else {
return("foo"); // whatever default value you want to return here
}
}
// use it like this:
function DoSomething() {
var val=$('#'+getClientId()).val();
.
.
.
}
Or, you can make a global function that will test it:
function isClientId() {
return(typeof window.clientId !== "undefined");
}
// use it like this:
function DoSomething() {
if (isClientId()) {
var val=$('#'+clientId).val();
.
.
.
}
}
if (typeof variable === 'undefined'). It's a great solution in my opinion.