Like you would do in php:
if (@$some_var_exists)
// do stuff
How would you do something like this in Javascript without getting an error?
Thanks
EDIT: Thanks for the answers. However, the problem I'm trying to solve is how to check if a variable exists when it's deep in a object, for example:
if (someObj.something.foo.bar)
// This gives an error in the browser if "someObj.something.foo" is not defined.
Check each part of the chain:
if (someObj && someObj.something && someObj.something.foo && someObj.something.foo.bar) {
// stuff
}
Because the expression is evaluated from left to right, and returns as soon as it finds false, it will not cause an error. So if "someObj" exists, but "sometObj.something" does not, it will return false and never execute the test for someObj.something.foo that would throw an error.
To check if a variable is defined, you could do:
if(self.somevar) {
...
}
As pointed out by Mister in the comments, the self
part is important here.
Or, if you wish to be more explicit, you could do:
if(typeof somevar != "undefined") {
...
}
The way you are checking the PHP var is also not very neat or really the best practice as the @
error suppressor is expensive and not necessary in this case. You could use isset
like this:
if(isset($some_var_here)) {
...
}
EDIT:
For your more specific problem, I think @Ryan Watkins answer is the way to do it, although I'd have to wonder why you put yourself in such a position anyways. :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With