19

This snippet results in a JavaScript runtime error: (foo is not defined)

if (foo) {
    // ...
}

I have to define foo first, like so:

var foo = foo || null // or undefined, 0, etc.

... And only then can I do:

if (foo) {
    // ...
}

Why is that?


Update:

This was somewhat of a brainfart on my side of things: 'fcourse you can't access a variable which is not allocated.

Fun stuff that you can do a typeof() on an undefined variable thou. I'm gonna accept miccet's answer since I think it's the most elegant solution.

1
  • This 2ality article mentions different recommended ways of checking for undefined, including interpreting it as falsy in boolean contexts. Commented Jun 20, 2017 at 13:44

6 Answers 6

27

I sense you are asking because you are aware that javascript seems to allow undefined variables in some situations (ie no runtime errors) and not in others.

The reasoning is as follows: javascript always throws an error on checking undefined variables, but never throws an error on checking undefined properties, as long as you only use one level of indirection.

Example:

// throws runtime error
if(foo) {
    // ...
}

// does not throw runtime error
if(window.foo) {
    // ...
}

// does not throw runtime error
var obj = {};
if(obj.foo) {
    // ...
}

// throws runtime error
if(obj.foo.bar) { // going two levels deep, but foo is undefined
    // ...
}

Hope that clears it up a bit.

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

Comments

19

You'll have to define it, to be able to check it for a value. In this case you're checking weather it's true. This variable is obviously not set to anything at all, same as null in C# and Nothing in VB for example.

If you must, debugging issues or whatever, you could check if the variable is undefined like this:

if (typeof(variable) == "undefined")

3 Comments

Nice little snippet. Very elegant. Will keep that in mind. It's weird that you can do a typeof() on an undefined variable, but not: if (undefinedVariable !== null).
Yea I've found this one quite handy. I guess the reason is because you look at it rather than into it, if that makes sense.
Doesn't seem to work on nested nodes. So for example if (typeof(object.node) == "undefined") will give a TypeError exception.
1

That would be because you're now defining it with:

var foo = foo || null

Why don't you define it in the first place? That seems pretty straightforward to me (unless I'm missing something).

Using a variable before it's created (or set to something) is bad programming practice, and should be avoided. My advice is to not use that trick to ensure it is set to something but to track down the logic error and fix it.

Comments

0

It seems strange question to me. Lets say I wanted to call a function:-

thing();

If thing hasn't be defined anywhere surely I would expect it to fail.

Why would you expect to use a variable called foo without defining it anywhere in your code?

Comments

0

I find this a bit of a strange question. To answer it I think it's best to ask the question the other way round...

What would be the expected result of

if (foo) {
    // ...
}

where foo is not defined as a variable?

I think the only possible answer is that the if would always evaluate to false and you'd never execute that block.

Asking a more direct question to you, why would you expect code to work which refers to variables that don't exist and have not had values assigned? What is foo in the context you define above?

Bottom line is that without the declaration the subsequent statement does not have any meaning. foo is not a term which can be evaluated on its own so you have to give the interpreter a context for the reference to foo so it can evaluate it.

There are languages which automatically create variables for you when they are first assigned (python and VB share that dangerous trait) but even those will not be able to evaluate a variable prior to assignment, so the interpreters throw errors.

If you had a compiler it would have told you about this too...

Comments

0

This is not a strange question coz I'm on the same boat :p

I reach here after googling "javascript use variable undefined". I got confuse coz I've seen somewhere that people can simply use undefined variable in a loop.

Maybe I saw it on different language


I've found it. The first codes successfully executed while the second codes runtime error.

First Codes:

test();
function test() { x = 4; }
console.log(x); //this produce 4

Second Codes:

test();
function test() { x[0] = 1; }
console.log(x[0]);

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.