I have a JavaScript file named index.js. This javascript file provides the procedural code associated with index.html. My index.html file is pretty basic. It looks like the following:
<!DOCTYPE html>
<html>
<body>
<script type="text/javascript" src="index.js"></script>
<script type="text/javascript">
@if (ViewBag.IsGood()) {
<text>
INFORMATION = { version: '<%= version%>', timestamp: '<%= timestamp%>' };
</text>
}
runInit();
</script>
</body>
</html>
In my index.html.js file, I have the following
function runInit() {
if (INFORMATION === undefined) {
INFORMATION = { version: 'Unknown' };
}
// Keep going
}
As you can see, sometimes INFORMATION gets set. Sometimes, it doesn't. Everything works when INFORMATION is set. When it is not set, I receive an error that says 'ReferenceError: Can't find variable: INFORMATION'. I'm confused by this because I think I'm checking to see if the property exists correctly. Apparently, I'm not.
In JavaScript, how do I ensure that a variable exists? That is my big concern. I don't want to have to rearrange my code. I really want to do it this way. I feel like I'm doing it correctly. However, I'm still getting an error.
Thanks.
You can use the typeof
operator:
so like this
typeof foo; //returns "undefined";
so to check if something is undefined
if(typeof INFORMATION==="undefined"){
INFORMATION={version:"Unknown"};
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With