0

Let's say I have the following object:

const a = {a: 1, 0: 2};
delete a.a; // this works
delete a.0; // this errors (I suppose expecting a['0'] and not a[0])

Does the method deletion form of obj.key only allow deletion of a string key? And if it's a non-string type, is the only way of doing deletion via the key lookup method of obj[key] ?

1 Answer 1

1

According to MDN:

In the object.property syntax, the property must be a valid JavaScript identifier.

... where ...

... identifiers are case-sensitive and can contain Unicode letters, $, _, and digits (0-9), but may not start with a digit.

So, answering your question, property with name 0 can be only accessed with key notation.

Sign up to request clarification or add additional context in comments.

5 Comments

I see. So in that case, is the most common way to delete a non-string object using the lookup syntax? Are there other ways as well, or that's the only way?
Only using key notation, i.e. delete obj[non-identifier].
And to clarify, except in the case of symbols, all keys will be strings. Just, in this case, it's being coerced from a number when you declare it
@dave I see, so even doing {0: 2} will give me {'0': 2}? I just cannot use property notation because a leading 0 is not allowed as a legal identifier?
@David542 exactly - if you do Object.keys({0: 2}) you'll get ["0"]. It's only because when using dot notation the property must be a valid JavaScript identifier

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.