Thursday, May 9, 2024
 Popular · Latest · Hot · Upcoming
79
rated 0 times [  86] [ 7]  / answers: 1 / hits: 26360  / 16 Years ago, tue, february 24, 2009, 12:00:00

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.


More From » javascript

 Answers
9

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)

[#99936] Tuesday, February 17, 2009, 16 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
ravenl

Total Points: 338
Total Questions: 107
Total Answers: 112

Location: Belize
Member since Mon, Jun 20, 2022
2 Years ago
ravenl questions
Thu, Feb 18, 21, 00:00, 3 Years ago
Tue, Jan 12, 21, 00:00, 3 Years ago
Tue, Mar 17, 20, 00:00, 4 Years ago
;