In JavaScript, the following gives an error:
{ __proto__: [] } instanceof Array;
If I surround it in (brackets)
it has no error:
({ __proto__: [] } instanceof Array);
Why is this?
In JavaScript, the following gives an error:
{ __proto__: [] } instanceof Array;
If I surround it in (brackets)
it has no error:
({ __proto__: [] } instanceof Array);
Why is this?
When the interpreter sees a {
, by default, it will think that you're declaring a new block, such as
{ console.log('foo'); }
As a result:
{ __proto__: [] } instanceof Array
doesn't make much sense - you can't instanceof
a block.
But when it's wrapped in parentheses, the interpreter knows to expect a value inside the parentheses, not a block - so it evaluates everything inside as an expression instead, and (properly) parses { __proto__: [] }
as an object.
This is exactly the same reason why, when destructuring to already assigned variables, you have to put parentheses around the line:
let x, y; ({x, y} = { x: 'foo', y: 'bar'}); console.log('done ' + x);
works, but it doesn't without the ()
:
let x, y; {x, y} = { x: 'foo', y: 'bar'}; console.log('done ' + x);