Search code examples
javascriptecmascript-6destructuring

Why does the expression {x}.x throw error by itself, but within an expression it doesn't?


I have been reading about object initialization on mdn and came across the following example:

const a = "foo";
const b = 42;
const c = {};

// Shorthand property names
const o = { a, b, c };

// In other words,
console.log(o.a === { a }.a); // true

What is surprising to me is that {a}.a gives error by itself:

const a = "foo";
const b = 42;
const c = {};

// Shorthand property names
const o = { a, b, c };

// In other words,
console.log(o.a === { a }.a); // true

console.log({a}.a); // all good
"foo"; //all good
//but the following gives error
{a}.a; 


Solution

  • A { after === starts an object initilizer which creates an object.

    You can put .a after an object to access a property of it.


    A statement that starts with a { is a block.

    You can't put a .a after a block. It doesn't make sense.