简体   繁体   中英

Is there any difference between ({}) and {} in javascript?

let obj1 = {
    a: 1,
    b: 2,
    c: 3
};
let obj2 = ({
    a: 1,
    b: 2,
    c: 3
});

Are obj1 and obj2 totally the same? Are they the same way to define an object in javascript?

Are obj1 and obj2 totally the same?

Yes. While they are not strictly equal in your question (they are not the same object references), they are essentially identical.

Is there any difference between ({}) and {} in javascript?

Yes. I know two situations off the top of my mind where this could make a difference.


First, you might have encountered this syntax in ES6 arrow functions before:

let array = [1, 2, 3, 4, 5];

let mappedArray = array.map(value => ({
    original: value,
    double: value * 2
}));

In here it does make a difference, as curly brackets by themselves would be interpreted as the boundaries of the function passed as the argument of map . That is, without the extra brackets, you would need:

array.map(value => {
    return {
        original: value,
        double: value * 2
    };
});

As a side-note, both of the above are identical to the following (except for the handling of this , which is not hindered by ES6 arrow syntax):

array.map(function (value) {
    return {
        original: value,
        double: value * 2
    };
});

Second, an object literal expression by itself is invalid in JavaScript, because the curly brackets are interpreted as the opening and closing brackets of a block .

So while this is a syntax error:

{
    a: 1,
    b: 2,
    c: 3
}

... the following is not (although it's absolutely useless by itself):

({
    a: 1,
    b: 2,
    c: 3
})

The simple answer is no . There is no difference. You can omit the brackets and get the exact same result.

它们完全相同,实际上你可以在第二种情况下省略()。

In your example they are exactly the same. Parenthesis are useless to declare obj2 in this case.

Parenthesis in programming (when evaluating a value) act like in equations, so having:

let obj1 = {
    a: 1,
    b: 2,
    c: 3
};
let obj2 = ({
    a: 1,
    b: 2,
    c: 3
});

Is the same as:

x = 2
x = (2)

in mathematics

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM