Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 696
oodavid Avatar asked Jan 06 '12 11:01

oodavid


People also ask

Can JSON have empty string key?

Tl;dr Yes it is.

Can an object key Be a string?

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.

Is empty string valid?

An empty string is not a valid json, then it fails.

Is Empty object Falsy value?

There are only seven values that are falsy in JavaScript, and empty objects are not one of them.


2 Answers

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.

like image 71
jAndy Avatar answered Oct 15 '22 06:10

jAndy


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.

like image 22
pimvdb Avatar answered Oct 15 '22 08:10

pimvdb