I've been tinkering with objects and seemingly you can have '' (an empty string) as a property name, like so:
o = { '': 'hello', 1: 'world', 'abc': ':-)', }; console.log(o['']);
Seems to work just fine, however I'm curious to know, is this really valid? I've poked at the ECMA specs and asked our ever-knowledgeable friend Google variations of the question and my conclusion is that I don't know.
My sources
http://www.jibbering.com/faq/faq_notes/square_brackets.html
Tl;dr Yes it is.
Object keys can only be strings, and even though a developer can use other data types to set an object key, JavaScript automatically converts keys to a string a value.
An empty string is not a valid json, then it fails.
There are only seven values that are falsy in JavaScript, and empty objects are not one of them.
Yes, technically its totally valid and you can safely use it. An object key needs to be a "string", which does not exclude an empty string.
If that is convenient or even useful is another story.
See Should I use an empty property key?
Since the 'empty string' is one of the falsy values
in ecmascript, consider the following example:
var foo = { ':-)': 'face', 'answer': 42, '': 'empty' }; Object.keys( foo ).forEach(function( key ) { if( key ) { console.log(key); } });
That snippet would only log :-)
and answer
. So that is one pitfall for doing this.
Seems fine (the (*)
apply to your case):
PropertyAssignment : (*) PropertyName : AssignmentExpression get PropertyName ( ) { FunctionBody } set PropertyName ( PropertySetParameterList ) { FunctionBody } PropertyName : IdentifierName (*) StringLiteral NumericLiteral StringLiteral :: " DoubleStringCharacters opt " (*) ' SingleStringCharacters opt '
Since the characters are optional, an empty string is valid.
Just note that IdentifierName
(i.e. without '
or "
) does not allow an empty string:
IdentifierName :: IdentifierStart IdentifierName IdentifierPart IdentifierStart :: UnicodeLetter $ _ \ UnicodeEscapeSequence
So, {'': 123}
is valid whereas {: 123}
is not.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With