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.

3
  • Where do you include index.html.js? Are you sure that src="index.html" in your HTML is not wrong? Commented Jan 2, 2014 at 20:16
  • if (typeof(INFORMATION)=='undefined') Commented Jan 2, 2014 at 20:17
  • @ComFreek - Fixed. Sorry. Commented Jan 2, 2014 at 20:22

1 Answer 1

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"};
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.