Solved

Basic Javascript, how to tell if a variable is undefined

Posted on 2015-01-09
7
148 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 82

Assisted Solution

by:Dave Baldwin
Dave Baldwin earned 25 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 76

Assisted Solution

by:arnold
arnold earned 25 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
Maximize Your Threat Intelligence Reporting

Reporting is one of the most important and least talked about aspects of a world-class threat intelligence program. Here’s how to do it right.

 
LVL 10

Accepted Solution

by:
Jeffrey Dake earned 450 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 76

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

Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

Avoid defining the variables in the global scope; trying to define them in a local function scope. Because:   • Look-up is performed every time a variable is accessed.   • Variables are resolved backwards from most specific to least specific scope…
I've been trying to accomplish this for a while and it just struck me yesterday how to accomplish this task. I have done searches all over the internet looking for ways to email pages from my applications and finally I have done it!!! Every single s…
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…

758 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

Need Help in Real-Time?

Connect with top rated Experts

18 Experts available now in Live!

Get 1:1 Help Now