0

I have this & it seems to work:

if ((obj.xxx != null) && (obj.xxx != "") && (typeof(obj.xxx) != "undefined"))

If only one if the statements is true will this equate to true or false? I feel I should be using the "or" operator but it breaks the widget.

if ((obj.xxx != null) || (obj.xxx != "") || (typeof(obj.xxx) != "undefined"))
Nicoll
  • 257
  • 1
  • 5
  • 16
  • 3
    I don't understand what you're trying to say. What is the expected behavior. Write the same on paper and then try to convert that to code using `&&` and `||` operators. FYI, if you use `||` that'll always be evaluated to `true`. Since OR need only one of the condition to be truthy. – Tushar Jan 28 '16 at 16:10
  • 2
    You might find `if (! (obj.xxx == null || obj.xxx == "" || typeof obj.xxx == "undefined"))` easier to read and understand. Hint: it's equivalent to your first condition – Bergi Jan 28 '16 at 16:12
  • 1
    Remember [De Morgan's laws](https://en.wikipedia.org/wiki/De_Morgan%27s_laws)... `(a != b) && (a != c)` is the same as `![ (a==b) || (a==c) ]`. – gen_Eric Jan 28 '16 at 16:13
  • _"I have this & it seems to work:"_ What is purpose of changing condition ? _"If only one if the statements is true will this equate to true or false?"_ `false` – guest271314 Jan 28 '16 at 16:15
  • It's part of a weather widget, the info is taken from an xml file, depends on where you are in the world the values can be different, it can be "undefined", or "". Sorry I asked here! I will use || – Nicoll Jan 28 '16 at 16:27
  • @Nicoll Is `"undefined"` a string ? What is expected result ? – guest271314 Jan 28 '16 at 16:29

2 Answers2

1

I would probably swap that all out for something like:

if (obj.xxx && obj.xxx !== "")

This ensures the object exists, is not null, and is not an empty string. and you'll want to read up on null vs undefined

willcwf
  • 712
  • 7
  • 10
1

You want to see if the item is null, nothing or undefined. If All of these are true, the statement is true. If even one is false, the statement is false. You should use or || so if any of the conditions is true, the condition is true.

LuvnJesus
  • 631
  • 4
  • 9