Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

Basic Javascript, how to tell if a variable is undefined

Posted on 2015-01-09
7
Medium Priority
?
159 Views
Last Modified: 2015-01-09
I thought I'd gotten this down pat, but I'm encountering a bizarre thing here. In my code sample is a function with no arguments. Within it, I test if the variable 'options' is undefined. But instead of the IF statement giving me the alert box, JavaScript itself is bombing out ("Uncaught ReferenceError: options is not defined") when it encounters the 'options' variable, and hence, does not even execute the alert function. Can anyone tell me what's wrong with this?

<!DOCTYPE html>
<html>
    <head>
        <title>Test</title>
        <meta charset="UTF-8">
        <script type="text/javascript">
            function test() { // no arguments
                if (options === undefined) // This is not working, why?
                    alert("options is not defined");
                else
                    alert("options is defined");
            }
        </script>

    </head>
    <body>

        <input type="button" id="btnShowBox" value="Show Box" onclick="test();" />
    </body>
</html>

Open in new window

0
Comment
Question by:elepil
7 Comments
 
LVL 84

Assisted Solution

by:Dave Baldwin
Dave Baldwin earned 100 total points
ID: 40541634
Because 'undefined' is not a value that you can make a comparison against.  Actually, it's just not a value.
Something like this works because it has a value to make a comparison against.  From http://www.w3schools.com/js/tryit.asp?filename=tryjs_comparison3
<!DOCTYPE html>
<html>
<body>

<p>Assign 5 to x, and display the value of the comparison (x === "5").</p>

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>

<script>
function myFunction() {
    var x = 5;
    if(x === "5") document.getElementById("demo").innerHTML = (x === "5");
   else  document.getElementById("demo").innerHTML = (x === "5");
}
</script>

</body>
</html>

Open in new window

0
 
LVL 80

Assisted Solution

by:arnold
arnold earned 100 total points
ID: 40541641
You should check for undefined using == undefined which is the same as checking if it is null.
A detailed explanation on the difference are outlined at
http://www.bloggingdeveloper.com/post/JavaScript-null-vs-undefined-The-Difference-between-null-and-undefined.aspx
0
 

Author Comment

by:elepil
ID: 40541642
Dave, thanks for responding.

I was testing the existence/nonexistence of a variable called 'option'. Your example assigns a value to 'x' and then tests it. It's not quite what I was asking.

Let me put a more realistic scenario. Let's say your project involves loading plugins and scripts written by others. You wanted to test if a variable 'a' has already been used or not before using it yourself. How would you test that the variable 'a' in code?
0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 11

Accepted Solution

by:
Jeffrey Dake earned 1800 total points
ID: 40541643
You need to use the typeof check.

<!DOCTYPE html>
<html>
    <head>
        <title>Test</title>
        <meta charset="UTF-8">
        <script type="text/javascript">
            function test() { // no arguments
                if (typeof options != "undefined") 
                    alert("options is defined");
                else
                    alert("options is not defined");
            }
        </script>

    </head>
    <body>

        <input type="button" id="btnShowBox" value="Show Box" onclick="test();" />
    </body>
</html>

Open in new window


Here is an article that explains the topic pretty well.  Look for the section titled How do I code against variables that may not exist? it explains it pretty well.

https://javascriptweblog.wordpress.com/2010/08/16/understanding-undefined-and-preventing-referenceerrors/

Hope this helps!
0
 

Author Comment

by:elepil
ID: 40541645
Arnold, if you tested out the short code I provided, you will see that == or === makes no difference. JavaScript just bombs out at the first encounter with the 'options' variable, as I stated in my post, giving the error message "Uncaught ReferenceError: options is not defined".
0
 
LVL 80

Expert Comment

by:arnold
ID: 40541647
Presumably each author is using only local/private variables with functions with defined API.
In that type of arrangement, ..
Alternatively using uniquely naming convention.
How many variables are you contemplating on testing and what the remedy if a variable you test

Not sure I understand the premise.
Presumably you have a site and there are several sources of scripts dealing with different aspects of site functionality that are included.
0
 

Author Closing Comment

by:elepil
ID: 40541648
Thanks to all who responded!
0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

In my daily work (mainly using ASP.net), I need to write a lot of JavaScript code. One of the most repetitive tasks I do are the jQuery Ajax calls. You know: (CODE) I don't know if for you it's the same, but for me is soooo tedious to write the …
JavaScript can be used in a browser to change parts of a webpage dynamically. It begins with the following pattern: If condition W is true, do thing X to target Y after event Z. Below are some tips and tricks to help you get started with JavaScript …
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…
Suggested Courses

885 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question