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.

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

5 Comments

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.
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.
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.
I know that. I'm just saying that the question title "Check if variable is (defined) ..." refers to my solution.
Alright, fair enough. The title says one thing, while the code says another.
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 Comment

I didn't know that second part.
1
var name = (typeof persons_name !== 'undefined' || !(!!persons_name)) ?
    persons_name :
    'John Doe';

Comments

0

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

Comments

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.