Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why are objects wrapped in parenthesis in JS?

Given the following example:

var foo = {
    root:
        ({
            key1: "Value1",
            key2: "Value2",
            key3: "Value3"
        })
    };

What is the difference compared to the following:

var foo = {
    root:
        {
            key1: "Value1",
            key2: "Value2",
            key3: "Value3"
        }
    };

In the first example there is an additional parens wrapping the object. What purpose does this serve? Does it have anything to do with scoping? Does it influence the execution in any way? Thank you!

like image 973
duck degen Avatar asked Sep 20 '12 09:09

duck degen


3 Answers

As per me, we should use square brackets to collect the objects. because, JavaScript will understand that it is an array.

Round brackets(used in example 1) are just validated by the javasript parser. When you try to access it, java script returns Only last object in the round brackets(like top object in the stack).

Try below script

var foo = {
    root1:
        {
            key1: "Value1",
            key2: "Value2",
            key3: "Value3"
        },
    root2:({
            key4: "Value4",
            key5: "Value5"
          },{
            key6: "Value6",
            key7: "Value7"
        }),
    root3:[
         {
            key8: "Value8",
            key9: "Value9"
          },{
            key10: "Value10",
            key11: "Value11"
          }
    ]
    };
    console.log(foo['root1']);  // returns object { key1, key2, key3}
    console.log(foo['root2']);  // returns only { key6,key7}
    console.log(foo['root3']);  //returns [ {key8,key9},{key10,key11}]
like image 32
Umesh Patil Avatar answered Sep 30 '22 16:09

Umesh Patil


There is absolutely no difference here.

AFAIK the one place where it does make a difference is when you evaluate an object literal on the console.

like image 168
Jon Avatar answered Sep 30 '22 16:09

Jon


They do nothing :) They're there for readability, although it's questionable if they achieve that aim.

like image 44
Nick Avatar answered Sep 30 '22 17:09

Nick