I need to pass a list of variable names in JavaScript and check if those variables exist. I tried the following but it doesn't seem to be doing the trick (JSFiddle here):
var test1 = 'test1';
var test2 = 'test2';
function checkVariable(variableNameList) {
for (var iterator = 0; iterator < variableNameList.length; iterator++) {
var variableName = variableNameList[iterator];
if (typeof window[variableName] === 'undefined') {
alert('Variable ' + variableName + ' is not defined');
} else {
alert('Variable ' + variableName + ' is defined');
}
}
}
checkVariable(['test1', 'test2', 'test3']);
I'm trying to get the resulting alerts:
- Variable test1 is defined.
- Variable test2 is defined.
- Variable test3 is not defined.
It seems easy to fix using the trick below but is there any other way to achieve this? Is declaring global variables under window
the only way to track them?`
window.test1 = 'test1';
window.test2 = 'test2';
Are there better ways to do this or is this the right approach?
Vanilla JS only answers please.