JavaScript gives you a lot of ways to declare objects. When you have most of the data available at hand, the most convenient (in my opinion) is as follows:
var person = {
name: 'John',
age: 23
}; // "object literal syntax"
A curious thing about this syntax is that it is identical to this:
var person = {
'name': 'John',
'age': 23
}; // "object literal syntax"
That is, you can use quotes or omit them for the property names.
When comparing that to the way setting a single property works, you have two options:
person.birthday = "January 12"; // "dot syntax"
or
person['birthday'] = "January 12"; // "array syntax"
The "dot syntax" only works when the right operand is the actual property name. If you want to use a variable for the property name, you have to use "array syntax", i.e.:
var prop = "birthday";
person[prop] = "January 12";
Now, is it possible to use a variable for the property name in the "object literal syntax"? Since it doesn't matter if you quote the property names, there doesn't seem to be an obvious way to use a variable there. I'm looking for something like this:
var prop = "birthday";
var person = {
name: 'John',
age: 23,
(prop): 'January 12'
};
Here I'm using (prop) as the imaginary syntax used to express that this is a variable and not a literal string.
Thanks.
Methods—setting functions as properties of objects. In JavaScript, you can use functions as values, just like numbers, strings, and objects. That means you can pass them as arguments, return them from other functions, and set them as properties of objects.
Introduction. JavaScript is an interpreted, object-oriented language that has two main data types: primitives and objects. This data within JavaScript is contained as fields (properties or variables) and code (procedures or methods).
The function name property of the javascript object is used to return the name of the function. This name property of the function is only readable and cannot be altered. The name of the function which was given when the function was created is returned by Function.name.
In ES6, the computed property name is a part of the object literal syntax, and it uses the square bracket notation. When a property name is placed inside the square brackets, the JavaScript engine evaluates it as a string. It means that you can use an expression as a property name.
No, this will not work, that is why, if you are dynamically setting property names, array like notation is suggested and used.
var k='propertyname';
object[k]="value";
this works while using the dot notation to set index or property name from vatiable is not possible.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With