5

Using Firefox, working on a Firefox extension, I continually get a javascript warning:

reference to undefined property mySidebar.context.netProgress

I have tried multiple ways of testing the value:

if (mySidebar.context.netProgress === undefined) {

And

if (typeof mySidebar.context.netProgress == "undefined") {

And

if (!mySidebar.context.netProgress) {

And

if (mySidebar.context.netProgress == undefined) {

However the error console in Firefox continues to give me the warning on the same line every time, the line in question is the line that I posted the code from above. The actual check for the value is causing the warning.

I also put an alert to check the value of mySidebar.context, which is always an object, so it is not from the parent that I'm getting the warning.

Any ideas?

Purge
  • 647
  • 4
  • 12

2 Answers2

6

As Swingley said, you can use Object.prototype.hasOwnProperty() to check for existence of a direct property on an object. This won't work for properties inherited from the prototype chain, however. For both situations, inherited and direct, you can use the in operator:

if ("netProgress" in mySidebar.context) {
Andy E
  • 338,112
  • 86
  • 474
  • 445
3

Try object.hasOwnProperty()

if (mySidebar.context.hasOwnProperty("netProgress")) {
Andy E
  • 338,112
  • 86
  • 474
  • 445
Derek Swingley
  • 8,734
  • 5
  • 32
  • 33
  • +1, I hope you don't mind me adding an example to your post. Note that this won't work for properties inherited through the prototype chain. – Andy E Sep 24 '10 at 17:05
  • 2
    Just note that `hasOwnProperty` checks for the *existence* of a property, the property could exist *and* its value could be `undefined`, see also: [Difference between undefined and not being defined in Javascript](http://stackoverflow.com/questions/3420071/difference-between-undefined-and-not-being-defined-in-javascript/3420160#3420160) – Christian C. Salvadó Sep 24 '10 at 17:12
  • Thanks CMS, this is fine as is, as I'm using this to check if the property exists before I try to add the property. WHen I remove the property, I use delete so it will work well for me. – Purge Sep 24 '10 at 17:15