Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 788
Searene Avatar asked Dec 24 '22 17:12

Searene


1 Answers

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
})
like image 85
John Weisz Avatar answered Jan 07 '23 19:01

John Weisz