I am a JavaScript learner and want to know what is the difference between
var obj1 = {
attribute1 : 1
};
var obj2 = {
"attribute1" : 1
};
console.log(obj1.attribute1);
console.log(obj2.attribute1);
Both of them prints 1. Is there a major difference among them?
They are equivalent in your case.
Internally, they are the same.
What could change is the way you can access them with your code.
When using strings (quoted properties), you can actually use more exotic names for your properties :
var obj3 = {
"attribute with space": 1,
"123AttributeStartingWithANumber": 1,
}
In my example, you cannot access those attribute names via the obj1.attributeName
syntax (but you can with the brackets notations : obj1["attribute with space"]
or obj1["123AttributeStartingWithANumber"]
.
This is because "attribute with space" or "123Attribute" are not valid identifiers in JS.
Note that in your example you can also use the bracket notation :
console.log(obj1["attribute1"]);
console.log(obj2["attribute1"]);
In summary, to quote deceze's comment :
Quoted properties and bracket notation always work, unquoted properties and
.
dot access is shorthand for when your property name is a valid identifier.
There is no difference.
Object literal syntax allows you to use a string or an identifier to provide the property name.
A string allows you to use characters (such as or
.
) which are not allowed in an identifier, but attribute1
has none of those characters in it.
You can make object keys with space in them if you declare them as strings:
var obj1 = {
attribute1 : 1 // but you cannot say my attribute1: 1 it will throw syntax error
};
var obj2 = {
"my attribute1" : 1
};
console.log(obj1.attribute1);
console.log(obj2.attribute1);
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