I tried to read the current state of my JavaScript by checking if a particualr variable had been defined:
if (app!=undefined) {...}
much to my surprise, app turned out to be defined and referred to an element in the DOM that had id="app".
Once JavaScript set its own variable, that reference disappeared. Deleting the variable brings back the dom-reference.
What gives? Or, to give a more specific question: Why is that so, how is it defined, and how can I check for the existence of a variable that turns out to be null / false / undefined if the variable hasn't been defined regardless of what IDs are part of the DOM?
ETA: https://jsbin.com/jehoxodeqi/edit?html,output
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>scope test</title>
</head>
<body>
<script type="text/javascript">
console.log ("--1");
try {
console.log (domId);
}
catch (e) {
console.log (e);
}
if (typeof domId === 'undefined' || !domId) {
console.log ("desired behavour.");
}
</script>
<div id="domId">DOM ID 1</div>
<script type="text/javascript">
console.log ("--2");
if (typeof domId === 'undefined' || !domId) {
console.log ("desired behavour... alas, it is defined.");
}
console.log (domId);
if (typeof domId === 'undefined' || !domId) {
console.log ("desired behavour... alas, it is defined.");
}
domId = "some String";
console.log ("--3");
console.log (domId);
delete domId;
console.log ("--4");
console.log (domId);
domId.remove();
console.log ("--5");
try {
console.log (domId);
}
catch (e) {
console.log (e);
}
console.log ("-- end --");
</script>
</body>
</html>
This shows what I've been trying to do originally.
I would expect for the variable to only be defined once I actually declare it in code. So, is there a purpose behind this, and if so, why is the variable name space dynamically overloaded by the DOM?