Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do a "soft" if condition check in Javascript

Tags:

javascript

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.
like image 374
adamJLev Avatar asked Nov 27 '22 05:11

adamJLev


2 Answers

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.

like image 192
Ryan Watkins Avatar answered Dec 09 '22 17:12

Ryan Watkins


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. :)

like image 32
Paolo Bergantino Avatar answered Dec 09 '22 18:12

Paolo Bergantino