5

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.

user2871401
  • 1,867
  • 5
  • 22
  • 24

1 Answers1

9

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"};
}
ComFreek
  • 29,044
  • 18
  • 104
  • 156
scrblnrd3
  • 7,228
  • 9
  • 33
  • 64