As you can see, an object property in JS is actually an index key of a array associative, then every code symbol (which can be naturally confused with an object variable) used to access a property is actually a string with the name of this symbol. So you can access:
obj.propriedade
or
obj["propriedade"]
or
var nome = "propriedade";
obj[nome];
or
obj[prompt()]; //desde que digite propriedade quando pedir o dado
All the same, it works.
So when you access through an expression, be a variable, a prompt()
crazy like I used, or in a way that you calculate the text of string used, you are using a computed property name.
You can see more details on JS native objects are associative arrays?. See also.
Example:
var pessoa = {
nome: "João",
animais: {
cachorro: "Rex",
gato: "Pipoca",
}
}
console.log(pessoa["animais"]["gato"]);
I put in the Github for future reference.
People are dazzled by this when they discover and begin to do things that are daunting and unnecessary, in general having an easier, more performative, more robust, or at least more correct way of doing the same. And we can still talk about more secure when using on the server, at least in some cases.
As seen you can access a property according to a user input. But imagine how dangerous it is to give this chance without a very strong validation. It is very easy for the user to enter with a wrong data and the code to break because of this.
A consequence of this can be seen in Why the behavior of the undefined variable is different from the undefined property?.
Some people use it to save code typing or to show that it is "very smart" and makes code unreadable and difficult to maintain. It’s a way of generalizing code, but it almost always doesn’t look good.
So if you really need access to a property to be done in some way to be determined at the time of execution this mechanism may be useful.
I’ve abused it so much in other languages that today I’m sure it’s not really necessary. So as object properties I see no advantage in using it except for laziness, distraction or if I’m making a framework that needs a generalization of how to proceed, for example an object to be created based on some external information, such as a JSON for example. This is a case where you do not know how the object is composed before you receive it. There you can create an object access mechanism without knowing its properties. You can’t do much, but you can access all the properties in a generic way. If it is only to make a display of all content of the object for example, you can make a code using a computed name.
You can use creativity to do some cool things, but almost always will be abuse.
These computed names are much more useful when using a array normal associative and not one that has become an object like in Javascript. There a dictionary application for example has the keyword and the dictionary description as value, it makes a lot of sense. A example.