1

Got confused by this behaviour. I thought doing something like:

if (variable name)
{
    ... do this...
}

should work. However if the variable is not defined, I just get 'ReferenceError: Can't find variable: "variable name, and the else block won't even be executed. For example the following snippet that I got off another StackOverflow question doesn't work when I test it. Any suggestions?

if(persons_name) 
{
    var name = persons_name;
} 
else 
{
    var name = "John Doe";
}

4 Answers 4

3
if (typeof persons_name !== 'undefined') {
  ...
} else {
  ...
}

Note that you don't need braces with typeof.

5
  • Code like this obfuscates the actual issue of referencing a non-existent variable. And it isn't equivalent to the test for "falsey" values in the question.
    – user113716
    Commented Aug 15, 2011 at 21:23
  • 1
    Well the author didn't specify anything about false values, but talked about variable existence. If you want to check if a variable is defined, my code is right.
    – ldiqual
    Commented Aug 15, 2011 at 21:34
  • if (variable name) is a test for no "falsey" values, not merely a test for existence or not undefined. The typeof persons_name !== 'undefined' doesn't deal with the fact that you're trying to incorrectly reference an undeclared variable. It skirts the issue with a hack. A better solution is to heed the information in the error, and declare the variable properly.
    – user113716
    Commented Aug 15, 2011 at 21:48
  • 1
    I know that. I'm just saying that the question title "Check if variable is (defined) ..." refers to my solution.
    – ldiqual
    Commented Aug 15, 2011 at 21:55
  • Alright, fair enough. The title says one thing, while the code says another.
    – user113716
    Commented Aug 15, 2011 at 22:06
2

Unlike a property, an unqualified name has to be defined before you can use it. So you if you were looking for a global variable persons_name you could write

if (window.persons_name)

and it would evaluate to undefined if persons_name didn't exist. Alternatively, you can simply declare persons_name if you expect it to exist.

var persons_name;

This won't change the value of persons_name if it already exists.

1
  • I didn't know that second part.
    – aepheus
    Commented Aug 15, 2011 at 21:12
1
var name = (typeof persons_name !== 'undefined' || !(!!persons_name)) ?
    persons_name :
    'John Doe';
0

by saying var name; you define the variable; and by saying var name = "john doe"; you assign it a value.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.