Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript - Check to see if variable exists [duplicate]

Tags:

javascript

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.

like image 759
user2871401 Avatar asked Jan 02 '14 20:01

user2871401


1 Answers

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"};
}
like image 138
scrblnrd3 Avatar answered Sep 17 '22 13:09

scrblnrd3