Can I have a JavaScript object key without a value

If you do something like if (myobj.flagged), then if your value of flagged is true, the test passes. If the flagged property doesn't exist, then you get undefined which is falsy. So it works with flagged:true, flagged:false and even no flagged property. So use true, and omit the property altogether when it's not supposed to be there (so for...in would work in that case).


The JSON specification won't let you create a key in an object without some value, and there isn't a definition of "undefined" (you can see here that the keywords are null, true, and false). If you're looking for a simple flag value, then your alternate approach could be:

if(object.key) // this would mean that the object has "key" and it is set 
               // to a truthy value.

Your other alternative might be something like:

if(key in object && object[key]) // Verifies key exists and has truthy value

Now, that being said, in JavaScript, you can be a little more expressive. For example:

> var k;
undefined
> var o = {k:k}
undefined
> o
Object {k: undefined}
> console.log('k' in o)
true