JavaScript object property names can be any string, including having spaces in the name. However, object property names that are not valid JavaScript identifiers, can only be:
- Specified using quotes, and;
- Accessed using the bracket property accessor notation.
For example, the following is a valid property name:
const obj = { 'Foo Bar': 123 }; console.log(obj['Foo Bar']); // 123
You can even have spaces at start or the end of the property name:
const obj = { ' Foo Bar ': 123 }; console.log(obj[' Foo Bar ']); // 123
This post was published (and was last revised ) by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.