Get in touch
or send us a question?

Coding experience series

To day we discuss about convention of naming object property in javascript.

In javascript, an object is usually declared like that:

example = {propertyName: “propertyValue”, otherName: “otherValue”}

or example1 = {“propertyName”: “propertyValue”, “otherName”: “otherValue”}

In two case, it works same. You can access property of object not only “.” operator but “[]” like that: example.propertyName === example[“propertyName”] === “propertyValue” and example1.propertyName === example1[“propertyName”] === “propertyValue”.

Declaration object in two manner maybe same, but are they exactly same?

The answer is no.

First , we should remember what value a property of object should receive. It can be identified name, string or number literal.

The first manner, propertyName is identified name. It follow javascript convention for identified name. Such that, -hieu is not correct identified name. When you’re naming property of object with an incorrect identified name, error occur and you can’t access anything. When you use “.” operator, it refer to identified name and it is checked before used.

The second manner, I use string for property name. It accepts any string. If we use “.” operator, it’s converted in to identified name and checked before operate. So, assumes we want to name property with incorrect identified name like that 12A we should use  string name. Example : var example = {“12A”: 27};

and use [] to access it: example[“12A”] === 27

Otherwise , property name can accept number literal like 12e2. You don’t use quote to declare it and you access it with [] and without quote.

Example: var example = {12e2: 24}

and example[12e2] === 24 or example[“1200”] === 24 because number literal first converted to string.

Above is three manner to declare property name of javascript object. And the string is most useful because it avoids to check identified name. Sometime we get trouble with it because identified name must be different from reversed word of javascript or some engine.

When you get ambiguous bug involved javascript object, try change it’s property to string and access with “[]”.