Javascript – Should objects be singular since arrays are plural

arraycode-qualityjavascriptnamingsemantics

Might be a silly question, but what is more logical:

object.actions.bark() or object.action.bark()?

Simply about plurality. I know arrays are usually pluralized. But if I were to be consistent; ideally, objects should be singular in nature, right?

I guess you could say my example was more of an associative array rather than an object. But doesn't an action object possess properties like bark(), much like how object object possesses the action property.

PS:

This is not opinion-based! It's a very objective inquiry on quality, documentation, and optimization. Imagine the chaos if this was subjective!

Best Answer

OK, so javascript has an oddity (amongst many) in that objects are in a way also collections.

But this shouldnt affect your naming. In OOP you should generally try to name objects as they would be called in real life and the Methods of those objects are things the object can do.

so:

dog.Bark()

cat.Meiow() 

etc

now you might have a complex object with sub objects or collections of objects. But again the naming should map to the real thing.

company.employees[5].fire()

It would be odd to create an object and use it like a collection

company.employees.bobsmith.fire()

even though such a thing is (in JS) equivalent to a collection of key value pairs

company.employees['bobsmith'].fire()

If you are going to write OO code in javascript its best to pretend that its strongly typed even though its not.