Solved

Basic Javascript, how to tell if a variable is undefined

Posted on 2015-01-09
7
150 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 83

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 77

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
Windows Server 2016: All you need to know

Learn about Hyper-V features that increase functionality and usability of Microsoft Windows Server 2016. Also, throughout this eBook, you’ll find some basic PowerShell examples that will help you leverage the scripts in your environments!

 
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 77

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

Master Your Team's Linux and Cloud Stack!

The average business loses $13.5M per year to ineffective training (per 1,000 employees). Keep ahead of the competition and combine in-person quality with online cost and flexibility by training with Linux Academy.

Question has a verified solution.

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

The task A number given should be formatted for easy reading by separating digits into triads. Format must be made inline via JavaScript, i.e., frameworks / functions are not welcome. So let’s take a number like this “12345678.91¿ and format i…
Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
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…

810 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