Louis Tran
Louis Tran

Reputation: 1156

What differences between these two ways of object declaration?

I was just wondering if there are any differences between these ways of JSON object declaration or they do the same thing? What is the standard (recommended) way to declare an object?

According to my test, they both give the same result.

let data1 = {
  "record_1": [1,2,3],
  "record_2": [4,5,6]
}

let data2 = {
  record_1: [1,2,3],
  record_2: [4,5,6]
}

console.log(data1);
console.log(data2);
console.log(data1.record_1);
console.log(data2.record_1);
console.log(data1.record_2);
console.log(data2.record_2);
console.log(JSON.stringify(data1));
console.log(JSON.stringify(data2));

Output:

{
record_1:(3) [...],
record_2:(3) [...]
}
{
record_1:(3) [...],
record_2:(3) [...]
}
(3) [
1,
2,
3
]
(3) [
1,
2,
3
]
(3) [
4,
5,
6
]
(3) [
4,
5,
6
]
{"record_1":[1,2,3],"record_2":[4,5,6]}
{"record_1":[1,2,3],"record_2":[4,5,6]}

Upvotes: 1

Views: 85

Answers (3)

huytc
huytc

Reputation: 1141

They're essentially the same. One difference is that when you use quotes, you can use special characters as key.

// invalid
const noQuotes = {
    key with spaces: 123
}

// valid
const withQuotes = {
    "key with spaces": 123
}

Upvotes: 1

Mamun
Mamun

Reputation: 68943

Object's property name are of type string, if you provide any other type then that is automatically converted to string.

var obj = {1: "one"}
var keyName = Object.keys(obj)[0];
console.log(`key Name ${keyName} and type is ${typeof keyName}`);

I will prefer the explicit way (using the quotes) of declaration as this will reduced the confusion (from the reader of the code).

Upvotes: 3

Shashank Vivek
Shashank Vivek

Reputation: 17504

Both of the declarations are valid in Javascript

let data1 = {
  "record_1": [1,2,3],
  "record_2": [4,5,6]
}

let data2 = {
  record_1: [1,2,3],
  record_2: [4,5,6]
}

but when it comes to JSON , data2 is invalid JSON syntax. You can verify at https://jsonlint.com/

One more diff is as below:

var obj = { "some key" : "Val" };  // Valid in JS

var obj = { some key : "Val" }; // invalid in JS

So for JS , both of these deceleration plays different role depending on the situation. Normally, data2 type declaration is widely used.

Upvotes: 3

Related Questions