Can JavaScript Object Property Name Have Underscores?

JavaScript object property names can be any string, including having underscores in the name. In fact, underscores are valid identifiers, which means that:

For example, the following is a valid property name:

const obj = { foo_bar: 'baz' };

console.log(obj.foo_bar); // 'baz'
console.log(obj['foo_bar']); // 'baz'

You can even have underscores at start or the end of the property name:

const obj = { _foo_: 'bar' };

console.log(obj._foo_); // 'bar'
console.log(obj['_foo_']); // 'bar'

This post was published 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.