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 obj1both obj2completely identical? Are they the same for defining an object in javascript?

+4
source share
4 answers

Are the tags obj1and obj2the same?

Yes. Although 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 that were in my mind where this could make a difference.


First, you might come across this syntax in the ES6 arrow function :

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

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

, , map. :

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

( this, ES6):

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

-, JavaScript, .

, :

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

... ( ):

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

. . .

+1

, () .

+1

. obj2.

Brackets in programming (when evaluating a value) act as in equations, therefore, having:

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

Same as:

x = 2
x = (2)

in math

+1
source

Source: https://habr.com/ru/post/1678103/


All Articles