0

I want a JS function that says whether a variable is set. I've defined isset() below.

It behaves strangely as described in the comments. Any ideas?

<html>
    <head></head>
    <body>
        <script type="text/javascript">

          function isset(variableName) {
            return typeof variableName != 'undefined';
          }

          a = 5;
          console.log(isset(a)); 
          console.log(isset(b)); // returns an error.
        </script>
    </body>
</html>
3
  • 3
    variableName is not the same as varname. Why try to access an undeclared variable? Commented Apr 5, 2013 at 21:45
  • Thanks! Now the output makes a lot more sense. Commented Apr 5, 2013 at 21:46
  • Since you changed the code, change your code comment too since it should now return true. Commented Apr 5, 2013 at 21:47

1 Answer 1

5

You need to perform the typeof check directly, not inside a function.

The reason is exactly the same one like in PHP (where your function would also break unless you used pass-by-reference):

isset(b) results in an exception being thrown because b is an undefined variable and passing it as an argument tries to read it which you cannot do. So the typef check is never executed.

Sign up to request clarification or add additional context in comments.

1 Comment

But inside of my isset() function, isn't there a local variable "a" with a value of 5?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.