Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Object Attribute With/Without quotes [duplicate]

Tags:

javascript

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?

like image 444
I.K. Avatar asked Oct 02 '18 10:10

I.K.


3 Answers

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.

like image 138
Pac0 Avatar answered Oct 19 '22 06:10

Pac0


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.

like image 40
Quentin Avatar answered Oct 19 '22 05:10

Quentin


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);
like image 1
Lazar Nikolic Avatar answered Oct 19 '22 06:10

Lazar Nikolic