1

This discussion was interesting but I have not been able to find something that's really going to work for me as I really just want to return true or false on an object's existence. I also really dislike verbose code and am looking for a simple and easy way to write things with minimum fuss.

For example it's suposed to be defined like this: Bigobject.option but that may not yet exist.

So I came up with this:

(!Bigobject.option == false), and this returns false if option isn't yet in existence, and true if it has been set to anything, including "nothing" or an empty string, object or array.

What I'd like to understand:

Is this a weird way to do it? Is it "legal"? Is this going to work consistently? Am I supposed to do it differently? Thanks for the help.

Community
  • 1
  • 1
tim
  • 3,823
  • 5
  • 34
  • 39

1 Answers1

1

To me it's about readability right after functionality.

(!Bigobject.option == false) is confusing to read in something that you haven't been working on. Try to read your code as someone whose never seen your code before. Can you predict what (!Bigobject.option == false) will return immediately?

I agree with the selected answer in the linked question, because you will (probably) know what (Bigobject.option === null) as a new reader.

To do what you are asking: return a bool of a variable's existence. I would use (typeof(Bigobject.option) === "undefined") unless it's possible for Bigobject.option to be the string "undefined"

Edit: I realized I didn't really answer your questions...

Is this a weird way to do it? Is it "legal"?

  • IMO it's weird but I'm pretty sure it's legal. jslint would warn you about "==".

Is this going to work consistently?

  • If Bigobject.option = false it will return false.

Am I supposed to do it differently?

  • I suggest you do.
jlaceda
  • 866
  • 6
  • 11
  • thanks for the write-up. in fact, theoretically it's possible for Bigobject.option to be the actual string "undefined", so I'm a bit worried about it. And what's wrong with "=="? – tim Apr 18 '12 at 23:26
  • Definitely use the null way in your situation. There's nothing wrong with "==", it just does type coercion before comparing, which might be convenient, but you have to be aware of what's being compared. http://www.jslint.com/lint.html#eqeq – jlaceda Apr 18 '12 at 23:40