Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people, just like you, are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
Solved

Basic Javascript, how to tell if a variable is undefined

Posted on 2015-01-09
7
151 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
Networking for the Cloud Era

Join Microsoft and Riverbed for a discussion and demonstration of enhancements to SteelConnect:
-One-click orchestration and cloud connectivity in Azure environments
-Tight integration of SD-WAN and WAN optimization capabilities
-Scalability and resiliency equal to a data center

 
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

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Article by: DanRollins
This article describes a JavaScript program that creates a maze made of hexagonal cells.  In Part 2 (http://www.experts-exchange.com/Programming/Languages/Scripting/JavaScript/A_7850-Hex-Maze-Part-2.html), we'll extend the program by adding a depth-…
This article will give core knowledge of JavaScript and will head in to your first JavaScript program. I am Durvesh Naik and I am here to deal with this series of JavaScript. I will teach you JavaScript in part wise , as its quite boring to read big…
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…

856 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