I have many js methods that uses global variables like:
function DoSomething() {
var val=$('#'+clientId).val();
.
.
.
}
DoSomething uses clientId variable. The problem is that clientId is not always declared and therefore I get an exception of undeclared variable.
I have many places like this and add if (typeof clientId == "undefined") check everywhere is a lot of work and code duplication (duplication of the check). Is there I can workaround it? for example use a method that returns null if the variable is not declared? (In such way I can control on the return value in case of an undefined for example)
Just an idea: all variables are properties of a namespace, up to the global namespace (in a browser, that’s
window). A property that’s not assigned evaluates toundefined. So if you want to know if a variable is assigned, you can useif (property in namespace). If it concerns a global variable in a browser:if (clientId in window). Now you can make a function out of that: