0

I'm comparing two objects like so:

if (obj1 !== null && obj2 !== null) {
    // do thing 1
} else if (obj1 == null && obj2 == null) {
    // also do thing 1
} else if (obj1 !== null) {
    // return obj1
} else {
    // return obj2
}

It feels really inelegant to include four lines for all four scenarios presented by the two objects/whether they exist. Is there a cleaner way to present this? Thanks!

YPCrumble
  • 20,703
  • 15
  • 86
  • 149
  • So it's doing in one case and returning in another? If it was all returning, you could do it in one line. – Popnoodles Jun 01 '14 at 15:16
  • @Popnoodles Correct, though would be interested to see that line! – YPCrumble Jun 01 '14 at 15:17
  • `return (obj1 || obj2);` http://jsfiddle.net/D7Zvk/ – Popnoodles Jun 01 '14 at 15:19
  • to check If an object exists use typeOf, see this example http://stackoverflow.com/questions/2703102/typeof-undefined-vs-null, use null only if your sure the obj has been declared – saj Jun 01 '14 at 15:24

2 Answers2

2

Here's a bit of a shortcut that uses the negation operator to turn both obj references into a boolean and you can then just compare the booleans:

if (!obj1 == !obj2) {
    // do thing 1
} else {
    return obj1 || obj2;
}

Explanation:

!obj1 == !obj2 will evaluate to true when either both obj1 and obj2 are truthy or falsey, but not if one is truty and the other falsey. So, if both are null, this will evaluate to true and if both are not null, this will evaluate to true, but if only one is null, then it will evaluate to false.

return obj1 || obj2 will return which ever is truthy (e.g. non-null).

Demo: http://jsfiddle.net/jfriend00/T7a3u/

jfriend00
  • 580,699
  • 78
  • 809
  • 825
1

This will reduce few liines:

if ((obj1 && obj2) || (!obj1 && !obj2)) {
    // do thing 1
}
else
    return (obj1 || obj2);
Jyoti Puri
  • 1,196
  • 8
  • 16