oodavid
oodavid

Reputation: 2326

Can I use an empty string as an object identifier?

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

Upvotes: 39

Views: 15637

Answers (2)

jAndy
jAndy

Reputation: 236022

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.

Upvotes: 36

pimvdb
pimvdb

Reputation: 154848

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.

Upvotes: 5

Related Questions