Solved

Basic Javascript, how to tell if a variable is undefined

Posted on 2015-01-09
7
155 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
[X]
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
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 79

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
SharePoint Admin?

Enable Your Employees To Focus On The Core With Intuitive Onscreen Guidance That is With You At The Moment of Need.

 
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 79

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

Optimize your web performance

What's in the eBook?
- Full list of reasons for poor performance
- Ultimate measures to speed things up
- Primary web monitoring types
- KPIs you should be monitoring in order to increase your ROI

Question has a verified solution.

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

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…
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

626 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